进行微信公众号相关开发,获取access_token是首要一步,因为access_token是公众号的全局唯一接口调用凭据。公众号调用各接口时都需使用access_token。
access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。更多关于access_token的讲解和说明请参阅微信公众平台技术文档。
本文通过demo的方式简单的演示如何通过appid(第三方用户唯一凭证)和appsecret(第三方用户唯一凭证秘钥)获取access_token。①封装实体类AccessToken:
package com.ldl.cn.wx;
public class AccessToken {
private String token;
private int expireIn;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getExpireIn() {
return expireIn;
}
public void setExpireIn(int expireIn) {
this.expireIn = expireIn;
}
}
②编写工具类
package com.ldl.cn.wx;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
public class Utils {
private static final String APPID = "wx***********";
private static final String APPSECRET = "71dcc**************";
private static final String URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
public static JSONObject doGetStr(String url){
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try{
HttpResponse response = defaultHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.parseObject(result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
public static AccessToken getAccessToken(){
AccessToken accessToken = new AccessToken();
String url = URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
JSONObject jsonObject = doGetStr(url);
if(jsonObject !=null){
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpireIn(jsonObject.getInteger("expires_in"));
}
return accessToken;
}
}
③编写测试类:
package com.ldl.cn.wx;
public class Test {
public static void main(String[] args) {
AccessToken token = Utils.getAccessToken();
System.out.println("token------>>>"+token.getToken());
System.out.println("expireIn------>>>"+token.getExpireIn());
}
}
测试效果: