TokenThread.java 1.72 KB
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
package com.lyms.talkonlineweb.task;

import com.alibaba.fastjson.JSONObject;
import com.lyms.talkonlineweb.util.HttpUtil;

public class TokenThread implements Runnable{
public static String appId = "wxd3c36244d006cb90";

public static String appSecret= "fc80b5dd03a581a088adcd2c65a7e10a";

public static String accessToken = null;

public void run(){
while (true){
try{
accessToken = this.getToken();
if(null!=accessToken){
System.out.println(accessToken);
Thread.sleep(7000 * 1000); //获取到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=" + this.appId
+ "&secret=" + this.appSecret;
String tokenJsonStr = HttpUtil.doGetPost(getTokenApi, "GET", null);
JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
String token = tokenJson.get("access_token").toString();
System.out.println("获取到的TOKEN : " + token);
return token;
}
}