92 lines
2.9 KiB
Plaintext
92 lines
2.9 KiB
Plaintext
package com.jysoft;
|
||
|
||
import javax.servlet.ServletException;
|
||
import javax.servlet.http.HttpServlet;
|
||
|
||
import com.jysoft.weChat.util.HttpUtil;
|
||
import com.jysoft.weChat.util.Wechatconfig;
|
||
import com.jysoft.weChat.vo.AccessTokenVo;
|
||
|
||
import net.sf.json.JSONObject;
|
||
|
||
public class AccessTokenServlet extends HttpServlet {
|
||
|
||
/**
|
||
* 每间隔两个小时,获取微信accessToken
|
||
*/
|
||
private static final long serialVersionUID = 119868412918946078L;
|
||
|
||
@Override
|
||
public void init() throws ServletException {
|
||
System.out.println("-----启动AccessTokenServlet-----");
|
||
super.init();
|
||
|
||
new Thread(new Runnable() {
|
||
@Override
|
||
public void run() {
|
||
while (true) {
|
||
try {
|
||
// 获取accessToken
|
||
Wechatconfig.accessToken = getAccessToken();
|
||
// 获取成功
|
||
if (Wechatconfig.accessToken != null) {
|
||
// 获取成功时,根据access_token获取jsapi_ticket
|
||
getJsapiTicket();
|
||
// 获取到access_token 休眠7000秒,大约2个小时左右
|
||
Thread.sleep(7000 * 1000);
|
||
} 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) {
|
||
e.printStackTrace();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}).start();
|
||
}
|
||
|
||
// 获取access_token 接口
|
||
@SuppressWarnings("static-access")
|
||
public static AccessTokenVo getAccessToken() {
|
||
HttpUtil netHelper = new HttpUtil();
|
||
/**
|
||
* 接口地址为https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET,其中grant_type固定写为client_credential即可。
|
||
*/
|
||
String Url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", Wechatconfig.appId, Wechatconfig.appSecret);
|
||
// 此请求为https的get请求,返回的数据格式为{"access_token":"ACCESS_TOKEN","expires_in":7200}
|
||
String result = netHelper.getHttpsResponse(Url, "");
|
||
|
||
System.out.println("获取到的access_token=" + result);
|
||
|
||
JSONObject jsonObject = new JSONObject().fromObject(result);
|
||
|
||
AccessTokenVo token = new AccessTokenVo();
|
||
|
||
token.setExpireSecond(jsonObject.getInt("expires_in"));
|
||
token.setTokenName(jsonObject.getString("access_token"));
|
||
|
||
return token;
|
||
}
|
||
|
||
// 获取jsapi_ticket
|
||
@SuppressWarnings("static-access")
|
||
private void getJsapiTicket() {
|
||
HttpUtil netHelper = new HttpUtil();
|
||
String Url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + Wechatconfig.accessToken.getTokenName() + "&type=jsapi";
|
||
// 此请求为https的get请求,返回的数据格式为{"access_token":"ACCESS_TOKEN","expires_in":7200}
|
||
String result = netHelper.getHttpsResponse(Url, "");
|
||
|
||
JSONObject jsonObject = new JSONObject().fromObject(result);
|
||
|
||
Wechatconfig.ticket = jsonObject.getString("ticket");
|
||
}
|
||
|
||
}
|