java 获取 token 代码 事例
时间: 2023-12-04 19:00:34 浏览: 123
获取token是在进行接口调用时的重要步骤,下面是一个使用Java语言获取token的示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TokenExample {
public static void main(String[] args) {
String tokenUrl = "https://example.com/api/token";
String clientId = "your_client_id";
String clientSecret = "your_client_secret";
try {
URL url = new URL(tokenUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
String requestBody = "grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(requestBody);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String token = response.toString();
System.out.println("Token: " + token);
} else {
System.out.println("Failed to get token. Response code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,此代码仅是一个示例,实际情况下需要根据具体的接口和授权方式进行调整。在该例子中,我们使用了HTTP POST请求向指定的token获取接口发送了包含客户端ID和客户端秘钥的请求体,得到了返回的token数据,并将其打印输出。在实际使用中,可能还需要对获取到的token进行解析和存储以备后续接口调用使用。
阅读全文