JAVA获取微信access_token(接口调用凭据)

在微信小程序的开发中,后端直接请求微信的大部分业务都要使用到access_token
access_token通过微信提供的接口获取,目前获取一次的有效期是7200秒
官方提供的接口:
在这里插入图片描述
使用思路:
1.如果程序中使用到access_token的地方非常非常少,直接请求到参数然后使用就可以,可以不用存储(偷懒的方法)
2.将access_token存入数据库,程序每隔固定的时间刷新(注意有效期是2小时,控制在1.5小时左右刷新较好),需要使用到这个参数时直接从数据库获取

获取access_token的代码:

控制层逻辑:

String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
						+ “你的appid”
						+ "&secret="
						+ "你的小程序secret";
String result = HttpUtil.sendGet(url);
JSONObject object=JSON.parseObject(result);
String Access_Token = object.getString("access_token");//这就是access_token

HttpUtil:

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

    private static final CloseableHttpClient httpclient = HttpClients.createDefault();

    /**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {

        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

JSONObject :

fastjson-1.2.44.jar(百度上搜索就有)
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值