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

1、什么是access_tokenjava

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

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

技术文档中建议服务器

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

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

2、调用access_token请求说明微信公众平台

使用https请求:GETthis

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

请求成功后返回JSON数据包spa

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

错误时会返回错误缘由

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

3、实现思路

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

3、实现代码

公用类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);
        }                
    }    
}
相关文章
相关标签/搜索