java 获取 长期有效的 access_token 代码示例
时间: 2024-06-10 14:07:04 浏览: 182
自己写的一个可以获取到token的小案例
以下是Java获取长期有效的access_token的代码示例:
```java
class MyAccessToken {
修改为自己的app和appsecret
private static final StringID = "your appid";
private static final String APPSECRET = "yoursecret";
// 获取access_token的接口
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
// access_token保存时间(单位:毫秒)
private static final long ACCESS_TOKEN_EXPIRE_TIME = 7200000; // 2小时
private static String access_token = null;
private static long access_token_create_time = 0;
/**
* 获取access_token
*
* @return access_token字符串
*/
public static String getAccessToken() {
// 判断是否超过保存时间
long now_time = System.currentTimeMillis() / 1000;
if (now_time - access_token_create_time > ACCESS_TOKEN_EXPIRE_TIME || access_token == null) {
JSONObject json = new JSONObject();
try {
json.put("grant_type", "client_credential");
json.put("appid", APPID);
json.put("secret", APPSECRET);
String result = HttpUtil.post(ACCESS_TOKEN_URL, json.toString());
JSONObject resultJson = new JSONObject(result);
if (resultJson.has("access_token")) {
access_token = resultJson.getString("access_token");
access_token_create_time = System.currentTimeMillis() / 1000;
} else {
throw new Exception(result);
}
} catch (Exception e) {
System.out.println("获取access_token出现错误:" + e.getMessage());
}
}
return access_token;
}
/**
* 发起HTTP请求获取返回结果
*
* @param url HTTP请求URL
* @param json HTTP请求body
* @return 返回结果字符串
* @throws Exception
*/
private static String post(String url, String json) throws Exception {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
result = EntityUtils.toString(httpEntity, "UTF-8");
}
}
httpClient.close();
return result;
}
}
```
请注意,如果要使用上述示例代码,需要替换APPID和APPSECRET为真实的值。
阅读全文