Springboot开发微信公众号(三)

Access_token的获取

一、 access_token的介绍

    access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_toke。access_token的有效时间时2个小时,并且调用的次数是有限的。建议在使用采用缓存处理。通过访问接口的方式获取access_token.在之后的开发中会很常见,调用接口。

二、 获取access_token

2.1 添加httpclient处理与redis的jar包

             <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
            </dependency>
	    <dependency>
		 <groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	    </dependency>

2.2根据api上的access_token,封装成bean

public class AccessToken {
	
	private String access_token;//获取到的凭证
	
	private int expires_in;//凭证有效时间

	public String getAccess_token() {
		return access_token;
	}

	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}

	public int getExpires_in() {
		return expires_in;
	}

	public void setExpires_in(int expires_in) {
		this.expires_in = expires_in;
	}
	
	
}	

2.3 添加redis缓存处理

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public final  class RedisUtil {
	 //Redis服务器IP
    private static String ADDR = "127.0.0.1";
    
    //Redis的端口号
    private static int PORT = 6379;
    
    //访问密码
    private static String AUTH = "123456";
    
    //可用连接实例的最大数目,默认值为8;
    //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
    private static int MAX_ACTIVE = 1024;
    
    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
    private static int MAX_IDLE = 200;
    
    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
    private static int MAX_WAIT = 10000;
    
    private static int TIMEOUT = 10000;
    
    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
    private static boolean TEST_ON_BORROW = true;
    
    private static JedisPool jedisPool = null;
    
    /**
     * 初始化Redis连接池
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);//如果你的redis设置了密码,在创建时添加AUTH参数
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 释放jedis资源
     * @param jedis
     */
    @SuppressWarnings("deprecation")
	public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }
}

2.4 处理调用接口post与get请求,获取access_token

方法中参数来自基本配置中的开发者ID与密码

package com.yuanjun.weixindemo.util;

import java.io.IOException;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import redis.clients.jedis.Jedis;

import com.yuanjun.weixindemo.bean.AccessToken;
import com.yuanjun.weixindemo.redis.RedisUtil;

/**
 * 
 * 类名称: WeiXinUtil
 * 类描述:
 * @author yuanjun
 * 创建时间:2017年12月8日下午4:38:42
 */
public class WeiXinUtil {
	/**
	 * 开发者id
	 */
	private static final String APPID = "换成你自己的appid";
	/**
	 * 开发者秘钥
	 */
	private static final String APPSECRET="开发秘钥";
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?"
			+ "grant_type=client_credential&appid=APPID&secret=APPSECRET";
	/**
	 * 处理doget请求
	 * @param url
	 * @return
	 */
	public static JSONObject doGetstr(String url){
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		JSONObject jsonObject = null;
		try {
			CloseableHttpResponse response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if(entity!=null){
				String result = EntityUtils.toString(entity);
				jsonObject = JSONObject.fromObject(result);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonObject;
		
	}
	/**
	 * 处理post请求
	 * @param url
	 * @return
	 */
	public static JSONObject doPoststr(String url,String outStr){
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		JSONObject jsonObject = null;
		try {
			httpPost.setEntity(new StringEntity(outStr, "utf-8"));
			CloseableHttpResponse response = httpclient.execute(httpPost);
			String result = EntityUtils.toString(response.getEntity(),"utf-8");
		    jsonObject =JSONObject.fromObject(result);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObject;
	}
	
	public static AccessToken getAccessToken(){
		System.out.println("从接口中获取");
		Jedis jedis  = RedisUtil.getJedis();
		AccessToken token = new AccessToken();
		String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
		JSONObject json = doGetstr(url);
		if(json!=null){
			token.setAccess_token(json.getString("access_token"));
			token.setExpires_in(json.getInt("expires_in"));
			jedis.set("access_token", json.getString("access_token"));
			jedis.expire("access_token", 60*60*2);
		}
		RedisUtil.returnResource(jedis);
		return token;
	}
	/**
	 * 获取凭证
	 * @return
	 */
	public static String  getAccess_Token(){
		System.out.println("从缓存中读取");
		Jedis jedis  = RedisUtil.getJedis();
		String access_token = jedis.get("access_token");
		if(access_token==null){
			AccessToken token = getAccessToken();
			access_token = token.getAccess_token();
		}
		RedisUtil.returnResource(jedis);
		return access_token;
	}
	
}

三、测试

import com.yuanjun.weixindemo.util.WeiXinUtil;

public class Test {
	public static void main(String[] args) {
		String access_token = WeiXinUtil.getAccess_Token();
		System.out.println("调用成功access_token:"+access_token);
	}
}








猜你喜欢

转载自blog.csdn.net/shenbug/article/details/78752888