JAVA获取微信access_token

官方文档

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
在这里插入图片描述

获取access_token 需要两个必要的参数,这两个参数在自己的微信公众平台可以看到
因为access_token有效期为两个小时,之后我们又得重复获取,所以我们在生成access_token给他保存下来,但是有的业务其实也不会生成很多access_token,所以这个存不存大家自己考虑就好,我的业务逻辑中就可以不用存的,但是我还是给他存了,常见的存properties文件中,redis中,数据库中,这个大家自行选择,我把我的access_token存入了数据库中,建相应的实体类,service,dao,表
下面附上我的代码
package com.jeesite.modules.utils;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.modules.accesstoken.entity.AccessToken;
import com.jeesite.modules.accesstoken.service.AccessTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * 获取access_token工具类
 */
@Component
public class AccessTokenUtil {

    @Autowired
    private AccessTokenService ats;

    private static AccessTokenService accessTokenService;

    @PostConstruct
    public void init(){
        accessTokenService = ats;
    }
    //synchronized static可以防止同时被多实例化
    public synchronized static String getAccessToken() throws IOException {
        //存放appId和secret 的properties文件
        String FileName = "weixin.properties";
        try {
            // 属性集合对象
            Properties prop = new Properties();
            //获取文件流
            InputStream fis = AccessTokenUtil.class.getClassLoader().getResourceAsStream(FileName);
            prop.load(fis);// 将属性文件流装载到Properties对象中
            fis.close();// 关闭流
            //获取appid,secret
            String appid = prop.getProperty("appid");
            String secret = prop.getProperty("secret");
            //从数据库中查出accessToken对象
            AccessToken accessToken = accessTokenService.getAccesstoken("1");
            //上次创建的时间
            Date creatTime = accessToken.getCreatTime();
            //格式化时间
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            String date = sdf.format(creatTime);
            //将时间转换成毫秒值
            long lastTime = sdf.parse(date).getTime();
            //获取到现在的毫秒值
            long nowTime = System.currentTimeMillis();
            //如果时差大于1小时59分则重新获取access_token
            if(nowTime - lastTime > 59*60*1000){
                //获取token url
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + appid + "&secret=" + secret;
                //发送http请求得到json流
                JSONObject jobject = httpRequest(url);
                //从json流中获取access_token
                String  access_token = (String) jobject.get("access_token");
                Integer ei = (Integer) jobject.get("expires_in");
                String expires_in = ei+"";
                //保存access_token
                if (access_token != null ) {
                    Date d = new Date();
                    accessToken.setCreatTime(d);
                    accessToken.setAccessToken(access_token);
                    accessToken.setExpiresIn(expires_in);
                    accessTokenService.update(accessToken);
                }
                return access_token;
            }
                //如果没有过期则返回数据库中的access_token
                return accessToken.getAccessToken();
        } catch (Exception e) {
            return null;
        }


    }

    // 获取accesstoken
    public synchronized static JSONObject httpRequest(String requestUrl) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
                    .openConnection();

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod("GET");

            httpUrlConn.connect();

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}


在这里插入图片描述在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44212951/article/details/97375550
今日推荐