原有项目搭建 https://blog.csdn.net/Ay_Ly/article/details/85090034
我们这时就需要解决access_token的有效时间,思路有两个:
1.定时获取access_token ,将其保存在内存中;
2.定时获取access_token,将其保存到数据库中;
在sprigBoot下的定时,实例如下:
先创建一个task类,负责将获取到的access_token 保存到内存中:
定时任务 WeixinAccessTokenTask,
加入注解标注此为一个定时任务第一次延迟1秒执行,然后每7100s执行一次@Scheduled(initialDelay = 1000, fixedDelay = 7000*1000 )
package com.cn21.guard.task;
import com.cn21.guard.common.constants.WeixinConstants;
import com.cn21.guard.common.utils.WeixinCommenUtil;
import com.cn21.guard.entity.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class WeixinAccessTokenTask {
Logger logger = LoggerFactory.getLogger(WeixinAccessTokenTask.class);
@Autowired
private WeixinCommenUtil weixinCommenUtil;
// 第一次延迟1秒执行,当执行完后7100秒再执行
@Scheduled(initialDelay = 1000, fixedDelay = 5*1000 )
public void getWeixinAccessToken(){
try {
String token = weixinCommenUtil.getToken(WeixinConstants.APPID, WeixinConstants.APPSECRET).getAccess_token();
logger.info("获取到的微信access_token为"+token);
} catch (Exception e) {
logger.error("获取微信access_toke出错,信息如下");
e.printStackTrace();
this.getWeixinAccessToken();
}
}
}
在启动类上加入定时任务注解,启动时开启定时任务
package com.cn21.guard;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class GuardApplication {
public static void main(String[] args) {
SpringApplication.run(GuardApplication.class, args);
}
}
WeixinCommenUtil:获取access_token 的代码
package com.cn21.guard.common.utils;
import com.cn21.guard.common.constants.WeixinConstants;
import com.cn21.guard.entity.AccessToken;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class WeixinCommenUtil {
Logger logger = LoggerFactory.getLogger(WeixinCommenUtil.class);
@Autowired
private HttpRequestUtil httpRequestUtil;
// 获取access_token的接口地址(GET) 限2000(次/天)
private static String url=WeixinConstants.ACCESS_TOKEN_URL;
public AccessToken getToken(String appid, String appsecret){
AccessToken token=null;
//访问微信服务器的地址
String requestUrl=url.replace("APPID", appid).replace("APPSECRET", appsecret);
//HttpRequestUtil httpRequestUtil=new HttpRequestUtil();
//创建一个json对象
JSONObject json =httpRequestUtil.httpsRequest(requestUrl,"GET",null);
System.out.println("获取到的json格式的Token为:"+json);
//判断json是否为空
if (json!=null){
try{
token=new AccessToken();
//将获取的access_token放入accessToken对象中
token.setAccess_token(json.getString("access_token"));
//将获取的expires_in时间放入accessToken对象中
token.setExpires_in(json.getInt("expires_in"));
}
catch (Exception e){
token=null;
e.printStackTrace();
System.out.println("系统异常!");
}
}else {
token=null;
// 获取token失败
logger.error("获取token失败 errcode:{} errmsg:{}");
}
return token;
}
}
WeixinConstants:
public class WeixinConstants {
public static final String ACCESS_TOKEN_URL =
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
public static final String APPID = "xxxxxxxxx";
public static final String APPSECRET = "xxxxxxx";
}
HttpRequestUtil:
package com.cn21.guard.common.utils;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
@Component
public class HttpRequestUtil {
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect();
// 当有数据需要提交时
if (!StringUtil.isEmpty(outputStr)) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException e) {
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
}
MyX509TrustManager:
package com.cn21.guard.common.utils;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* 信任管理器
*
* @author zoutt
* @date 2018-12-19
*/
public class MyX509TrustManager implements X509TrustManager {
// 检查客户端证书
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
StringUtil:
package com.cn21.guard.common.utils;
public class StringUtil {
public static boolean isEmpty(String str) {
return str == null || str.trim().length() == 0;
}
}
实体类AccessToken:
package com.cn21.guard.entity;
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;
}
}
结果: