小程序获取access_token

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值