获取access token的java代码
时间: 2023-10-09 17:05:28 浏览: 98
以下是使用 Java 获取访问令牌(access token)的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class AccessTokenFetcher {
public static void main(String[] args) {
String clientId = "YOUR_CLIENT_ID";
String clientSecret = "YOUR_CLIENT_SECRET";
String tokenEndpoint = "TOKEN_ENDPOINT_URL";
String grantType = "client_credentials";
try {
// 构建请求参数
String query = String.format("grant_type=%s&client_id=%s&client_secret=%s",
URLEncoder.encode(grantType, StandardCharsets.UTF_8),
URLEncoder.encode(clientId, StandardCharsets.UTF_8),
URLEncoder.encode(clientSecret, StandardCharsets.UTF_8));
// 创建连接
URL url = new URL(tokenEndpoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.getOutputStream().write(query.getBytes(StandardCharsets.UTF_8));
// 发送请求并读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 解析响应JSON,提取access token
String accessToken = response.toString().split("\"access_token\":\"")[1].split("\"")[0];
// 打印access token
System.out.println("Access Token: " + accessToken);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请注意,你需要将 `YOUR_CLIENT_ID`、`YOUR_CLIENT_SECRET` 和 `TOKEN_ENDPOINT_URL` 替换为你自己的值。此示例使用了简单的 HTTP POST 请求来获取访问令牌,你可能需要根据具体的认证服务和 API 进行适当的调整。
阅读全文