JAVA 搭建获取微信TOKEN工具

web.xml配置信息

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name></display-name>
	
  	<servlet>  
	    <servlet-name>InitServlet</servlet-name>  
	    <servlet-class>com.xxx.wechat.token.InitServlet</servlet-class>  
	</servlet>  
  
  	<servlet-mapping>  
	    <servlet-name>InitServlet</servlet-name>  
	    <url-pattern>/initServlet.do</url-pattern>  
  	</servlet-mapping>
  	
  	<welcome-file-list>  
    	<welcome-file>index.jsp</welcome-file>  
 	</welcome-file-list>  
  
</web-app>

InitServlet

package com.xxx.wechat.token;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 获取微信Token接口
 */
public class InitServlet  extends HttpServlet{

	protected static Logger logger = LogManager.getLogger(InitServlet.class);
	
	private static final long serialVersionUID = 1L;  
  
    public void init() throws ServletException {  
        // 启动定时获取access_token的线程  
        new Thread(new TokenThread()).start();  
    }  

    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        request.setCharacterEncoding("UTF-8");  
        
        String accessToken =  TokenThread.accessToken;
        //String accessToken = WechatTools.getAccessToken();
        try {  
            OutputStream os = response.getOutputStream();  
            os.write(accessToken.getBytes("UTF-8"));  
            os.flush();  
            os.close();  
        } catch (Exception e) {  
        	logger.debug("InitServlet doGet token Exception:"+e);
        } 
    }
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

线程

package com.xxx.wechat.token;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 每1小时(微信端两小时内有效)获取一次Token
 */
public class TokenThread implements Runnable{

 	private static Logger log = LoggerFactory.getLogger(TokenThread.class);  
    public static String accessToken = null;  
  
    public void run() {  
        while (true) {  
            try {  
                accessToken = WechatTools.getAccessToken();  
                log.debug("获取access_token成功:", accessToken);  
                Thread.sleep(3600*1000); 
                log.debug("next start .....");  
            } catch (InterruptedException e) {  
                log.error("InterruptedException {}", e);  
            } catch (Exception e) {  
                log.error("Exception {}", e);  
            }  
        }  
    }  
}

WechatTools

package com.minxue.wechat.token;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.minxue.util.HttpConnectionUtil;
import com.minxue.util.JsonUtil;
import com.minxue.util.PropertisUtil;

/**
 * 微信推送工具类
 */
public class WechatTools {
	
	protected static Logger logger = LogManager.getLogger(WechatTools.class);
	
	private final static String appid = PropertisUtil.getInstance().getWxAppid();
	private final static String secret = PropertisUtil.getInstance().getWxSecret();
	
	private final static String WECHAT_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
	
	private static String access_token = "";
	
	/**
	 * 获取access_token
	 */
	public static String getAccessToken() {
		try{
			logger.debug("getAccessToken i(ss):" );
			//获取access_token
			String accessTokenURL = HttpConnectionUtil.AccessUrlGet(WECHAT_URL);
			logger.debug("new accessTokenResult URL :"+accessTokenURL);
			if(accessTokenURL != null && !accessTokenURL.equals("")){
				AccessToken accessToken = (AccessToken) JsonUtil.JsonToObject(accessTokenURL, AccessToken.class);
				if(accessToken != null){
					access_token = accessToken.getAccess_token();;
					logger.debug("new_access_token============:"+access_token);
				}else{
					logger.error("accessTokenResult error:"+accessToken);
				}
			}
		}catch(Exception e){
			logger.error("getAccessToken Exception:" + e);
		}
		return access_token;
	}

}

HttpConnectionUtil工具

package com.minxue.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 网络连接工具类
 * @version V1.0
 */
public class HttpConnectionUtil {

	/**
	 * 网络链接
	 * @param url 
	 * @param postString 参数
	 * @return String
	 */
	public static String AccessUrl(String url, String postString) {
		String result = null;
		HttpURLConnection conn = null;
		try {
			URL postUrl = new URL(url);
			conn = (HttpURLConnection) postUrl.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			conn.setConnectTimeout(2000);
			conn.setReadTimeout(2000);
			OutputStream os = conn.getOutputStream();
			os.write(postString.getBytes("utf-8")); // 往远程URL传递参数
			os.flush();
			os.close();
			int code = conn.getResponseCode();
			// 返回长度:"+conn.getContentLength());
			conn.getHeaderFields();
			conn.getContentLength();
			if (code == 200) {// 返回成功
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
				String line;
				StringBuffer buffer = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				result = buffer.toString();
			} else {
				result = "服务异常,错误码:"+code;
			}
		} catch (MalformedURLException e) {
			result = "服务异常:"+e.getMessage();
		} catch (IOException e) {
			result = "服务异常:"+e.getMessage();
		}finally{
			if(conn != null){
				conn.disconnect();
				conn=null;
			}
		}
		return result;
	}
	
	/**
	 * 网络链接
	 * @param url 
	 * @param postString 参数
	 * @return String
	 */
	public static String AccessUrlGet(String url) {
		String result = null;
		HttpURLConnection conn = null;
		try {
			URL postUrl = new URL(url);
			conn = (HttpURLConnection) postUrl.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			conn.setConnectTimeout(2000);
			conn.setReadTimeout(2000);
			int code = conn.getResponseCode();
			conn.getHeaderFields();
			conn.getContentLength();
			if (code == 200) {// 返回成功
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
				String line;
				StringBuffer buffer = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				result = buffer.toString();
			} else {
				result = "服务异常,错误码:"+code;
			}
		} catch (MalformedURLException e) {
			result = "服务异常:"+e.getMessage();
		} catch (IOException e) {
			result = "服务异常:"+e.getMessage();
		}finally{
			if(conn != null){
				conn.disconnect();
				conn=null;
			}
		}
		return result;
	}

}

微信凭证AccessToken

package com.minxue.wechat.token;


/**
 * 微信凭证
 */
public class AccessToken {
	
	/**
	 * 获取到的凭证
	 */
	private String access_token;
	
	/**
	 * 凭证有效时间,单位:秒
	 */
	private int expires_in;
	
	/**
	 * 创建一个新的实例 AccessToken.
	 *
	 */
	public AccessToken() {
		super();
	}

	/**
	 * @return access_token
	 */
	public String getAccess_token() {
		return access_token;
	}

	/**
	 * @param access_token the access_token to set
	 */
	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}

	/**
	 * @return expires_in
	 */
	public int getExpires_in() {
		return expires_in;
	}

	/**
	 * @param expires_in the expires_in to set
	 */
	public void setExpires_in(int expires_in) {
		this.expires_in = expires_in;
	}
	
}

因token接口请求每天有上线限制,使用该工具可以完成token的获取工作


版权声明:本文为weixin_31172555原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。