public class WxTokenFactory {
public static Map<String, String> wxtoken = new HashMap<String, String>(); //全局变量,存到内存当中
/**
* 根据有效期内存中存储微信access_token
* @return
*/
public static synchronized Map setTokenMap() {
if (wxtoken == null || wxtoken.isEmpty()) {//内存中没有
wxtoken = new HashMap<String, String>();
createToken(wxtoken);//重建
} else {
String token_yxq = wxtoken.get("token_yxq");//过期时间字符串
Calendar now = Calendar.getInstance();//当前时间
Calendar cal = Calendar.getInstance();//token过期时间
Date d;
try {
d = new SimpleDateFormat("yyyy-M-dd HH:mm:ss").parse(token_yxq);
cal.setTime(d);
int ret = now.compareTo(cal);//时间比较
if(ret >= 0) {//token过期
createToken(wxtoken);//重新获取
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return wxtoken;
}
/**
* 获取微信access_token
* @return
*/
public static String getToken() {
Map map = setTokenMap();
return (String) map.get("access_token");
}
/**
* 创建微信access_token 公众号的全局唯一票据
* @param wxtoken
* @return
*/
public static Map createToken(Map wxtoken) {
try {
String appid ="...";
String appsecret="...";
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret);
//使用POST方法
client.executeMethod(method);
//打印服务器返回的状态
if (method.getStatusCode()==200){
// 打印返回的信息
//System.out.println(method.getResponseBodyAsString());
JSONObject jsonObject = JSONObject.fromObject(method.getResponseBodyAsString());
String access_token = jsonObject.get("access_token").toString();
//System.out.println(access_token);
if(access_token != null && !"".equals(access_token)) {
wxtoken.put("access_token", access_token);
Calendar calendar = Calendar.getInstance();
//有效期提前一分钟[-60]
calendar.add(Calendar.SECOND, Integer.parseInt(jsonObject.get("expires_in").toString())-60);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd HH:mm:ss");
String token_yxq = sdf.format(calendar.getTime());
wxtoken.put("token_yxq", token_yxq);
} else {
wxtoken = null;
}
}
// 释放连接
method.releaseConnection();
} catch (Exception ex) {
ex.printStackTrace();
}
return wxtoken;
}
Access_token的存储
最新推荐文章于 2021-05-19 21:41:28 发布