public class WxTokenUtil {
private static String FileName = "WxTokenUtil.properties";
private static String APPID = "fsdafsd";
private static String APPSECRET = "dfsdsaf";
public synchronized static String getAccessToken() {
try{
// 文件获取token值及时间
Properties prop = new Properties();// 属性集合对象
InputStream fis =WxTokenUtil.class.getClassLoader().getResourceAsStream(FileName);
prop.load(fis);// 将属性文件流装载到Properties对象中
fis.close();// 关闭流
String access_token = prop.getProperty("access_token");
String expires_in = prop.getProperty("expires_in");
String last_time = prop.getProperty("last_time");
int int_expires_in = 0;
long long_last_time = 0;
try{
int_expires_in = Integer.parseInt(expires_in);
long_last_time = Long.parseLong(last_time);
}catch(Exception e){
}
long current_time = System.currentTimeMillis();
// 如果token时间超时,重新获取
if ((current_time - long_last_time) / 1000 >= int_expires_in) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ APPID + "&secret=" + APPSECRET;
JSONObject jobject = httpRequest(url);
String j_access_token = (String) jobject.get("access_token");
String j_expires_in = (String) jobject.get("expires_in");
//保存
if(j_access_token!=null && j_expires_in!=null){
prop.setProperty("access_token", j_access_token);
prop.setProperty("expires_in", j_expires_in);
prop.setProperty("last_time", System.currentTimeMillis()+"");
URL url_ = WxTokenUtil.class.getClassLoader().getResource(FileName);
FileOutputStream fos= new FileOutputStream(new File(url_.toURI()));
prop.store(fos, null);
fos.close();// 关闭流
}
return j_access_token;
} else {
return access_token;
}
}
catch(Exception e){
return null;
}
}
// --
public synchronized static JSONObject httpRequest(String requestUrl) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}