码迷,mamicode.com
首页 > 微信 > 详细

微信维护access_token

时间:2019-01-07 17:36:16      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:except   lse   hand   puts   throw   ast   generate   package   cache   

微信维护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 + "\n";
            }

            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

标签:except   lse   hand   puts   throw   ast   generate   package   cache   

原文地址:https://www.cnblogs.com/AngeLeyes/p/10233944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!