二维码

微信公众号开发二:获取access_token

1502 人阅读 | 时间:2018年12月14日 10:09

一、什么是access_token

微信公众平台技术文档中对access_token的解释:

access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

技术文档中建议

1.使用中控服务器统一获取刷新access_token,避免不同的业务逻辑各自刷新容易引起冲突;

2.access_token中有expire_in,目前是7200秒之内的值可以根据该值控制刷新access_token,刷新过程中中控服务器可以继续对外输出老的access_token,公众平台后台会保证在5分钟内新老access_token可以继续使用;

二、调用access_token请求说明

使用https请求:GET

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

请求成功后返回JSON数据包

{"access_token":"ACCESS_TOKEN","expires_in":7200}

错误时会返回错误原因

{"errcode":40013,"errmsg":"invalid appid"}

三、实现思路

通过HttpURLConnection实现https请求,获取到返回数据包后根据ACCESS_TOKEN保存到文本文件中供业务逻辑调用,expires_in中的时间控制刷新。

三、实现代码

公用类HttpsUtil用来调用http连接

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor. */package priv.liu.weichat.util;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.URL;import java.net.HttpURLConnection;import javax.net.ssl.HttpsURLConnection;import net.sf.json.JSONObject;/**
 *
 * @author liu */public class HttpsUtil {    
    /**
     * HttpsUtil方法https请求结果返回蔚json类型
     * @param Url http请求地址
     * @param Method http请求类型支持POST GET
     * @param Output
     * @return InputStream转换成JSONObject后返回
     * @throws Exception 
     */
    public JSONObject HttpsUtil(String Url,String Method,String Output) throws Exception{
        JSONObject jsonObject = null;
        URL conn_url =  new URL(Url);
        HttpURLConnection conn = (HttpsURLConnection)conn_url.openConnection();
        conn.setRequestMethod(Method);
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.connect();        //output获取access_token是不会用到
        if(Output != null){
            OutputStream  outputstream =conn.getOutputStream();            //字符集,防止出现中文乱码
            outputstream.write(Output.getBytes("UTF-8"));
            outputstream.close();
        }        //正常返回代码为200
        if(conn.getResponseCode()==200){
            InputStream stream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(stream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
        stream.close();
        conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        }
        System.out.println(conn.getResponseCode());        return jsonObject;
    }   
}

循环获取accesst_token代码

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor. */package priv.liu.weichat.token;import static java.lang.Thread.sleep;import net.sf.json.JSONObject;import priv.liu.weichat.util.HttpsUtil;/**
 *
 * @author liu */public class GetToken {    /**
     * @param args the command line arguments
     * @throws java.lang.Exception     */
    public static void main(String[] args) throws Exception {        // TODO code application logic here        //访问地址
        String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";        //appid
        String APPID = "wxf62ff5631358ef2e";        //appsecret
        String APPSECRET = "2af33a0092006148a5000ff06e9151bb";        
        String request_url = TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        HttpsUtil httpsUtil = new HttpsUtil();
        System.out.println(request_url);        int i = 0;        while(true){
            JSONObject jsonObject = httpsUtil.HttpsUtil(request_url,"GET",null);            if(null != jsonObject){
                String access_tocken = jsonObject.getString("access_token");
                String expires_in = jsonObject.getString("expires_in");                //获取到的access_tocken值可以写入到文本文件中供其他业务逻辑调用,实例中只打印了没有保存到文件
                System.out.println("获取成功"+"access_tocken="+access_tocken+"||expires_in="+expires_in);  
                i=Integer.parseInt(expires_in);
            }            //休眠1小时57分钟,提前三分钟获取新的access_token
            sleep((7200-180)*1000);
        }                
    }    
}

 

©著作权归作者所有:来自ZhiKuGroup博客作者没文化的原创作品,如需转载,请注明出处,否则将追究法律责任 来源:ZhiKuGroup博客,欢迎分享。

评论专区
  • 昵 称必填
  • 邮 箱选填
  • 网 址选填
◎已有 0 人评论
搜索
作者介绍
30天热门
×
×
本站会员尊享VIP特权,现在就加入我们吧!登录注册×
»
会员登录
新用户注册
×
会员注册
已有账号登录
×