1.第一次获取放设置过期时间放map
2.下次从map中获取,如果如果为空就请求微信api. 如果不为空,就拿上次存放的过期时间和现在时间做比对,如果过期时间早于当前时间,就重新获取。
protected synchronized AccessToken getAccessToken() {
AccessToken accessToken = (AccessToken)tokenMap.get(this.appid);
Long now = (new Date()).getTime();
if (accessToken == null || now > accessToken.getExpiresTimestemp()) {
accessToken = WechatUtils.getAccessToken(this.appid, this.secret);
tokenMap.put(this.appid, accessToken);
logger.info("new accessToken");
}
return accessToken;
}
public static AccessToken getAccessToken(String appid, String secret) {
if (appid != null && secret != null) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource cosmsservice = client.resource("https://api.weixin.qq.com/cgi-bin/token");
ClientResponse clientResponse = (ClientResponse)cosmsservice.queryParam("grant_type", "client_credential").queryParam("appid", appid).queryParam("secret", secret).get(ClientResponse.class);
if (clientResponse.getStatus() != 200) {
throw new IllegalStateException("status error:" + clientResponse.getStatus());
} else {
Map result = (Map)(new Gson()).fromJson((String)clientResponse.getEntity(String.class), Map.class);
if (result.get("errcode") != null) {
throw new WechatAccessException(result.get("errcode") + "", result.get("errmsg") + "");
} else {
long now = (new Date()).getTime();
return new AccessToken((String)result.get("access_token"), ((Double)result.get("expires_in")).longValue() * 1000L + now);
}
}
} else {
throw new IllegalArgumentException("appid or secret was null.");
}
}