package com.lyms.talkonlineweb.task;
import com.alibaba.fastjson.JSONObject;
import com.lyms.talkonlineweb.util.Constant;
import com.lyms.talkonlineweb.util.HttpUtil;
import com.lyms.talkonlineweb.util.StringUtil;
import com.lyms.talkonlineweb.util.WeiXinUtil;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
/**
* 获取到access_token
* 每1小时59获取一次token,保证长期有效。
* (微信公众号规定2小时token失效,每天只能获取2000次。)
*/
@Component
public class AccessTokenServlet extends HttpServlet implements Runnable {
public static String accessToken = null;
/**
* 启动后开启线程每1小时59获取一次token
* @throws ServletException
*/
@PostConstruct//部署时开启注释,启动线程
public void init() throws ServletException {
new Thread(new AccessTokenServlet()).start(); //启动线程
}
public void run(){
while (true){
try{
accessToken = this.getToken();
if(null!=accessToken){
Thread.sleep(1000 * 7000); //获取到access_token 休眠7000秒
}else{
Thread.sleep(1000 * 3); //获取的access_token为空 休眠3秒
}
}catch(Exception e){
System.out.println("发生异常:"+e.getMessage());
e.printStackTrace();
try{
Thread.sleep(1000 * 10); //发生异常休眠1秒
}catch (Exception e1){
}
}
}
}
/**
* 获取token
* 微信公众号
* @return token
*/
public String getToken() {
// 授予形式
String grant_type = "client_credential";
// 接口地址拼接参数
String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + Constant.GZ_APP_ID
+ "&secret=" + Constant.GZ_SECRET;
String tokenJsonStr = WeiXinUtil.repeatDoGetPost(getTokenApi, "GET", null);
if(StringUtil.isEmpty(tokenJsonStr)){
System.out.println("获取TOKEN :失败,repeatDoGetPost返回值为空>>>>>>>");
return null;
}
JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
String token = tokenJson.get("access_token").toString();
System.out.println("获取到的TOKEN : " + token);
return token;
}
}