Token定时获取
需要导入库:添加log4j(slf4j-api-1.5.10.jar,slf4j-log4j12-1.5.10.jar,log4j-1.2.15.jar,并且在src下添加log4j.properties),json-lib-2.2.1-jdk15.jar
第一步:新建包com.wtz.vo,新建类Token.java,添加接口访问凭证类
1 package com.wtz.vo; 2 3 /** 4 * @author wangtianze QQ:864620012 5 * @date 2017年4月23日 下午2:30:52 6 * <p>version:1.0</p> 7 * <p>description:接口访问凭证类</p> 8 */ 9 public class Token { 10 //接口访问凭证 11 private String accessToken; 12 //接口有效期,单位:秒 13 private int expiresIn; 14 15 public String getAccessToken() { 16 return accessToken; 17 } 18 public void setAccessToken(String accessToken) { 19 this.accessToken = accessToken; 20 } 21 public int getExpiresIn() { 22 return expiresIn; 23 } 24 public void setExpiresIn(int expiresIn) { 25 this.expiresIn = expiresIn; 26 } 27 }
第二步:找到包com.wtz.util,新建类MyX509TrustManager.java类,这个类是用来做https请求的证书信任管理器
1 package com.wtz.util; 2 3 import java.security.cert.CertificateException; 4 import java.security.cert.X509Certificate; 5 6 import javax.net.ssl.X509TrustManager; 7 8 /** 9 * @author wangtianze QQ:864620012 10 * @date 2017年4月23日 下午2:40:51 11 * <p>version:1.0</p> 12 * <p>description:证书信任管理器(用于https请求)</p> 13 */ 14 public class MyX509TrustManager implements X509TrustManager{ 15 16 @Override 17 public void checkClientTrusted(X509Certificate[] arg0, String arg1) 18 throws CertificateException { 19 // TODO Auto-generated method stub 20 21 } 22 23 @Override 24 public void checkServerTrusted(X509Certificate[] arg0, String arg1) 25 throws CertificateException { 26 // TODO Auto-generated method stub 27 28 } 29 30 @Override 31 public X509Certificate[] getAcceptedIssuers() { 32 // TODO Auto-generated method stub 33 return null; 34 } 35 }
第三步:在src下添加log4j.properties
1 log4j.rootLogger=info,console 2 log4j.appender.console=org.apache.log4j.ConsoleAppender 3 log4j.appender.console.layout=org.apache.log4j.PatternLayout 4 log4j.appender.console.layout.ConversionPattern=[%-5p] %m%n
第四步:找到包com.wtz.util,新建类WeixinUtil.java
1 package com.wtz.util; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStream; 8 import java.net.ConnectException; 9 import java.net.MalformedURLException; 10 import java.net.URL; 11 import java.security.KeyManagementException; 12 import java.security.NoSuchAlgorithmException; 13 import java.security.NoSuchProviderException; 14 15 import javax.net.ssl.HttpsURLConnection; 16 import javax.net.ssl.SSLContext; 17 import javax.net.ssl.SSLSocketFactory; 18 import javax.net.ssl.TrustManager; 19 20 import net.sf.json.JSONObject; 21 22 import org.slf4j.Logger; 23 import org.slf4j.LoggerFactory; 24 25 import com.wtz.vo.Token; 26 27 /** 28 * @author wangtianze QQ:864620012 29 * @date 2017年4月23日 下午5:08:02 30 * <p>version:1.0</p> 31 * <p>description:通用https请求工具类</p> 32 */ 33 public class WeixinUtil { 34 //需要导入库slf4j-api-1.5.10.jar和slf4j-log4j12-1.5.10.jar以及log4j-1.2.15.jar和log4j.properties 35 private static Logger log = LoggerFactory.getLogger(WeixinUtil.class); 36 37 //凭证获取(GET) 38 public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 39 40 /** 41 * 发送https请求 42 * 43 * @param requestUrl 请求地址 44 * @param requestMethod 请求方式(GET/POST) 45 * @param outputStr 提交的数据 46 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 47 */ 48 public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){ 49 //需要导入库json-lib-2.2.1-jdk15.jar 50 JSONObject jsonObject = null; 51 52 //创建SSLContext对象,并使用我们指定的信任管理器初始化 53 TrustManager[] tm = {new MyX509TrustManager()}; 54 try { 55 SSLContext sslContext = SSLContext.getInstance("SSL","SunJSSE"); 56 57 sslContext.init(null, tm, new java.security.SecureRandom()); 58 59 //从上述SSLContext对象中得到SSLSocketFactory对象 60 SSLSocketFactory ssf = sslContext.getSocketFactory(); 61 62 URL url = new URL(requestUrl); 63 64 HttpsURLConnection connection = (HttpsURLConnection)url.openConnection(); 65 66 connection.setSSLSocketFactory(ssf); 67 68 connection.setDoOutput(true); 69 connection.setDoInput(true); 70 connection.setUseCaches(false); 71 72 //设置请求方式(GET/POST) 73 connection.setRequestMethod(requestMethod); 74 75 //当outputStr不为null时向输出流写入数据 76 if(null != outputStr){ 77 OutputStream outputStream = connection.getOutputStream(); 78 outputStream.write(outputStr.getBytes("UTF-8")); 79 outputStream.close(); 80 } 81 82 //从输入流读取返回内容 83 InputStream inputStream = connection.getInputStream(); 84 InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 85 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 86 String str = null; 87 StringBuffer buffer = new StringBuffer(); 88 while((str = bufferedReader.readLine()) != null){ 89 buffer.append(str); 90 } 91 92 //释放资源 93 bufferedReader.close(); 94 inputStreamReader.close(); 95 inputStream.close(); 96 inputStream = null; 97 connection.disconnect(); 98 99 jsonObject = JSONObject.fromObject(buffer.toString()); 100 101 } catch (ConnectException e) { 102 log.error("连接超时:{}",e); 103 } catch (NoSuchAlgorithmException e) { 104 log.error("https请求异常:{}",e); 105 } catch (NoSuchProviderException e) { 106 log.error("https请求异常:{}",e); 107 } catch (KeyManagementException e) { 108 log.error("https请求异常:{}",e); 109 } catch (MalformedURLException e) { 110 log.error("https请求异常:{}",e); 111 } catch (IOException e){ 112 log.error("https请求异常:{}",e); 113 } catch (Exception e) { 114 log.error("https请求异常:{}",e); 115 } 116 117 return jsonObject; 118 } 119 120 /** 121 * 获取接口访问凭证 122 * 123 * @param appid 124 * @param appsecret 密钥 125 * @return 126 */ 127 public static Token getToken(String appid,String appsecret){ 128 Token token = null; 129 String requestUrl = token_url.replace("APPID", appid).replace("APPSecret", appsecret); 130 131 //发起GET请求获取凭证 132 JSONObject jsonObject = httpsRequest(requestUrl,"GET",null); 133 134 if(null != jsonObject){ 135 token = new Token(); 136 token.setAccessToken(jsonObject.getString("access_token")); 137 token.setExpiresIn(jsonObject.getInt("expires_in")); 138 } 139 140 return token; 141 } 142 }
第五步:找到包com.wtz.util下的Parameter.java类,修改增加appSecret
1 package com.wtz.util; 2 3 /** 4 * @author wangtianze QQ:864620012 5 * @date 2017年4月21日 下午9:27:50 6 * <p>version:1.0</p> 7 * <p>description:参数api</p> 8 */ 9 public class Parameter { 10 //token 11 public static String token = "wangtianze"; 12 //随机戳 13 public static String encodingAESKey = "X78dYU3MXpijKArRbiozTRq0jZZnjxxvuB4n8KJwRH1"; 14 //应用AppID 15 public static String appId = "wx9621c31e147dfdf9"; 16 //密钥 17 public static String appSecret = "a8eec7e642ecece4294daa18c8747035"; 18 }
第六步:找到包com.wtz.util,新建类TokenThread.java类
1 package com.wtz.util; 2 3 import org.slf4j.Logger; 4 import org.slf4j.LoggerFactory; 5 6 import com.wtz.vo.Token; 7 8 /** 9 * @author wangtianze QQ:864620012 10 * @date 2017年4月23日 下午9:30:53 11 * <p>version:1.0</p> 12 * <p>description:定义线程定时获取微信access_token</p> 13 */ 14 public class TokenThread implements Runnable{ 15 private static Logger log = LoggerFactory.getLogger(TokenThread.class); 16 //第三方用户唯一凭证 17 public static String appid = "wx9621c31e147dfdf9"; 18 //第三方用户唯一凭证密钥 19 public static String appsecret = "a8eec7e642ecece4294daa18c8747035"; 20 21 public static Token accessToken = null; 22 23 public static Token getAccessToken() { 24 return accessToken; 25 } 26 27 public static void setAccessToken(Token accessToken) { 28 TokenThread.accessToken = accessToken; 29 } 30 31 public void run(){ 32 while(true){ 33 accessToken = WeixinUtil.getToken(appid,appsecret); 34 try{ 35 if(null != accessToken){ 36 log.info("获取access_token成功,有效时长{}秒 token:{}",accessToken.getExpiresIn(),accessToken.getAccessToken()); 37 //休眠7000秒 38 Thread.sleep((accessToken.getExpiresIn() - 200)*1000); 39 }else{ 40 //如果accessToken为null,则60秒后再获取 41 Thread.sleep(60*1000); 42 } 43 } catch(InterruptedException e) { 44 try{ 45 Thread.sleep(60*1000); 46 } catch(InterruptedException e1) { 47 log.error("{}",e1); 48 } 49 log.error("{}",e); 50 } 51 } 52 } 53 }
第七步:修改web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>weixinValidation</display-name> 4 5 <servlet> 6 <servlet-name>InitGetTokenServlet</servlet-name> 7 <servlet-class>com.wtz.service.InitGetTokenServlet</servlet-class> 8 <init-param> 9 <param-name>appid</param-name> 10 <param-value>wx9621c31e147dfdf9</param-value> 11 </init-param> 12 <init-param> 13 <param-name>appsecret</param-name> 14 <param-value>a8eec7e642ecece4294daa18c8747035</param-value> 15 </init-param> 16 <load-on-startup>0</load-on-startup> 17 </servlet> 18 19 <servlet> 20 <servlet-name>LoginServlet</servlet-name> 21 <servlet-class>com.wtz.service.LoginServlet</servlet-class> 22 </servlet> 23 24 <servlet-mapping> 25 <servlet-name>LoginServlet</servlet-name> 26 <url-pattern>/api/login</url-pattern> 27 </servlet-mapping> 28 29 <welcome-file-list> 30 <welcome-file>index.jsp</welcome-file> 31 </welcome-file-list> 32 </web-app>
第八步:找到包com.wtz.service,新建类InitGetTokenServlet.java类
1 package com.wtz.service; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.http.HttpServlet; 5 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; 8 9 import com.wtz.util.TokenThread; 10 11 /** 12 * @author wangtianze QQ:864620012 13 * @date 2017年4月23日 下午8:21:28 14 * <p>version:1.0</p> 15 * <p>description:初始化定期获取Token的线程</p> 16 */ 17 public class InitGetTokenServlet extends HttpServlet{ 18 private static final long serialVersionUID = 1L; 19 private static Logger log = LoggerFactory.getLogger(InitGetTokenServlet.class); 20 @Override 21 public void init() throws ServletException { 22 //修改web.xml中配置的参数 23 TokenThread.appid = getInitParameter("appid"); 24 TokenThread.appsecret = getInitParameter("appsecret"); 25 26 log.info("微信 api appid:{}",TokenThread.appid); 27 log.info("微信 api appsecret:{}",TokenThread.appsecret); 28 29 //未配置appid和appsecret时给出提示 30 if("".equals(TokenThread.appid) || "".equals(TokenThread.appsecret)){ 31 log.error("appid and appsecret配置错误,请仔细检查!"); 32 }else{ 33 //启动定时获取access_token的线程 34 new Thread(new TokenThread()).start(); 35 } 36 } 37 }
Token定时获取完成