package com.yafengliang.api; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; /** * @Author : yafengliang * @Description: 获取Token * @Date : 2020-12-03 17:24 **/ public class AuthService { /** * @Description: 获取Token * @Author: liangyafeng **/ public static String getAuth(){ // 官网获取的 API Key 更新为你注册的 String clientId = "你自己的API Key"; // 官网获取的 Secret Key 更新为你注册的 String clientSecret = "你自己的 Secret Key"; return getAuth(clientId, clientSecret); } /** * @Description: 获取API访问token 该token有一定的有效期,需要自行管理,当失效时需重新获取. * @Author: liangyafeng * * @Param ak - 百度云官网获取的 API Key * @param sk - 百度云官网获取的 Securet Key **/ private static String getAuth(String ak, String sk) { String authHost = "https://aip.baidubce.com/oauth/2.0/token?"; String getAccessTokenUrl = authHost // 1. grant_type为固定参数 + "grant_type=client_credentials" // 2. 官网获取的 API Key + "&client_id=" + ak // 3. 官网获取的 Secret Key + "&client_secret=" + sk; try { URL realUrl = new URL(getAccessTokenUrl); // 打开和URL之间的连接 HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.err.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String result = ""; String line; while ((line = in.readLine()) != null) { result += line; } /** * 返回结果示例 */ System.err.println("result:" + result); JSONObject jsonObject = new JSONObject(result); String access_token = jsonObject.getString("access_token"); return access_token; } catch (Exception e) { System.err.printf("获取token失败!"); e.printStackTrace(System.err); } return null; } }

柒月只是个码农 LV4
2023年8月29日
我真的是小明 LV10
2023年3月21日
xopomo LV1
2023年3月10日
kevinyu168 LV1
2022年1月10日
刘强一 LV13
2021年10月28日
戒烟失败 LV3
2021年5月13日
lifanfanfan LV5
2021年4月22日
kakaka21 LV3
2021年2月8日
bflcf LV6
2021年1月5日
Web项目聚集地 LV24
2021年1月3日

新哥新奇士橙 LV5
1月26日
444105047 LV6
2024年11月27日
周周快乐快乐
2024年9月8日
暂无贡献等级
TY0165 LV20
2024年6月19日
kiliny
2024年6月5日
暂无贡献等级
3334004690 LV11
2024年5月28日
kenhomeliu LV29
2024年4月30日
tr1314qq LV17
2024年2月5日
haozhilang LV9
2023年10月23日
柒月只是个码农 LV4
2023年8月29日