场景:业务需要获取到access_token,然后去看了文档,并根据文档上的代码示例调用不成功
https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
使用以下代码示例能够轻松获取,只需要将clientId和clientSecret换成自己的apikey和secretkey就可以了。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class AccessToken{
public static void main(String[] args) {
String accessToken = getAccessToken();
System.out.println("Access Token: " + accessToken);
}
private static String getAccessToken() {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
String url = "https://aip.baidubce.com/oauth/2.0/token";
String grantType = "client_credentials";
String clientId = "11111111111111";
String clientSecret = "22222222222222222";
String apiUrl = String.format("%s?grant_type=%s&client_id=%s&client_secret=%s",
url, grantType, clientId, clientSecret);
URL apiURL = new URL(apiUrl);
connection = (HttpURLConnection) apiURL.openConnection();
connection.setRequestMethod("POST");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} else {
System.out.println("Error response code: " + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//取出返回的access_token
JSONObject jsonObject = JSON.parseObject(response.toString());
String accessToken = jsonObject.getString("access_token");
return accessToken;
}
}