1: access_token 是小程序全局唯一后台接口调用凭据,调用绝大多数后台接口时都需使用
2: 请求地址
GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
3: 请求参数
grant_type 填写 client_credential
appid 小程序唯一凭证,即 AppID,可在「微信公众平台 - 设置 - 开发设置」页中获得。(需要已经成为开发者,且帐号没有异常状态)
secret 小程序唯一凭证密钥,即 AppSecret,获取方式同 appid
4: 返回值
access_token 获取到的凭证
expires_in 凭证有效时间,单位:秒。目前是7200秒之内的值
errcode 错误码
errmsg 错误信息
官方文档 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
测试方法
@Test
public void doGetTestOne() {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
// CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//1: 创建httpClient的对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2: 创建Get请求
HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"); //appid 和 secret 换成自己的
//3:添加请求参数 (这里没有请求参数)
// 响应模型
CloseableHttpResponse response = null;
try {
// 4: 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 5: 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
//响应的内容为字符串,可以利用split(“\"”)方法的到数组,就可以得到自己想要的access_token的值
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 6: 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意: access_token最好进行缓存,默认的有效时间为7200s