微信维护access_token

Posted 猥琐熊花子酱

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信维护access_token相关的知识,希望对你有一定的参考价值。

微信维护access_token

package com.weixin.ys.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weixin.ys.constants.Constants;
import com.weixin.ys.entity.TemplateData;
import com.weixin.ys.entity.TemplateMessage;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
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;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AccessTokenCache {
    //主动调用的access_token
    public static String access_token;
    //主动调用的请求时间
    public static Date access_token_date;
    //token的有效时间,默认7200,用于判断是否超时,考虑网络延迟是的减小
    public static long accessTokenInvalidTime=7200L;


    /**
     * @return
     */
    public static String getTokenFromWx(){
        String token="";
        //判断当前已有access_token是否有效
        if(null==access_token||"".equals(access_token)||(new Date().getTime()-access_token_date.getTime())>=(accessTokenInvalidTime-200L)) {

            String httpsResponse = getHttpsResponse("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constants.APPID + "&secret=" + Constants.APPSECRET, null);

            System.out.println(httpsResponse);

            if(httpsResponse.contains("access_token"))
            {
                JSONObject json = JSON.parseObject(httpsResponse);
                accessTokenInvalidTime=Long.valueOf(json.getInteger("expires_in"));
                access_token=json.getString("access_token");
                access_token_date=new Date();
            }
        }
        return access_token;
    }



    public static String getHttpsResponse(String hsUrl, String requestMethod) {
        URL url;
        InputStream is = null;
        String resultData = "";
        try {
            url = new URL(hsUrl);
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            TrustManager[] tm = {xtm};

            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, tm, null);

            con.setSSLSocketFactory(ctx.getSocketFactory());
            con.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });


            con.setDoInput(true); //允许输入流,即允许下载

            //在android中必须将此项设置为false
            con.setDoOutput(false); //允许输出流,即允许上传
            con.setUseCaches(false); //不使用缓冲
            if(null!=requestMethod && !requestMethod.equals("")) {
                con.setRequestMethod(requestMethod); //使用指定的方式
            }
            else{
                con.setRequestMethod("GET"); //使用get请求
            }
            is = con.getInputStream();   //获取输入流,此时才真正建立链接
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bufferReader = new BufferedReader(isr);
            String inputLine = "";
            while ((inputLine = bufferReader.readLine()) != null) {
                resultData += inputLine + "
";
            }

            Certificate[] certs = con.getServerCertificates();

            int certNum = 1;

            for (Certificate cert : certs) {
                X509Certificate xcert = (X509Certificate) cert;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultData;
    }

    static X509TrustManager xtm = new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }
    };

}

以上是关于微信维护access_token的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序获取二维码(直接上代码)https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN

Koa2微信公众号开发 获取access_token

云调用:一行代码直通微信开放接口能力

生成 小程序 URL Scheme

微信第三方登录接口流程

微信公众平台开发-access_token获取及应用(含源码)