定义一个实体类,存放accessToken和过期时间
package com.zhu.information;
public class AccessToken {
private String accessToken;
private long expireTime;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public long getExpireTime() {
return expireTime;
}
public void setExpireTime(long expireTime) {
this.expireTime = expireTime;
}
public AccessToken(String accessToken, String expireIn) {
super();
this.accessToken = accessToken;
//过期时间=当前时间+微信公众号获取的过期时间
this.expireTime = System.currentTimeMillis()+Integer.parseInt(expireIn)*1000;
}
public boolean isExpired() {
return System.currentTimeMillis()>expireTime;
}
}
获取accessToken的测试代码
package utils;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.junit.Test;
import com.zhu.information.AccessToken;
import net.sf.json.JSONObject;
import sun.net.URLCanonicalizer;
public class util {
private static final String GET_TOKE_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private static final String APPSECRET="wxb836d07b8de2a4f2";
private static final String APPID="7eeba7d02c9d67623be6c7e6bda806f0";
private static AccessToken at;
public static String get(String url) {
try {
System.out.print(url);
URL urlObj=new URL(url);
URLConnection connection=urlObj.openConnection();
InputStream is=connection.getInputStream();
byte[] b=new byte[1024];
int len;
StringBuffer sb=new StringBuffer();
while((len=is.read(b))!=-1) {
sb.append(new String(b,0,len));
}
return sb.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 获取token
*/
private static void getToken() {
String url=GET_TOKE_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
String tokenStr=util.get(url);
JSONObject jsonObject=JSONObject.fromObject(tokenStr);
String token=jsonObject.getString("access_token");
String expireIn=jsonObject.getString("expires_in");
at=new AccessToken(token, expireIn);
}
public static String getAccessToken() {
//判断时间是否过期
if(at==null||at.isExpired()) {
getToken();
}
return at.getAccessToken();
}
@Test
public void testToken() {
System.out.println(getAccessToken());
}
}