1. 程式人生 > >java 微信公眾平臺之獲取access_token

java 微信公眾平臺之獲取access_token

獲取access_token:

公眾號可以使用AppID和AppSecret呼叫介面來獲取access_token

http請求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
/**  
 * 獲取access_token  
 * access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 
 * @param appid 憑證  
 * @param appsecret 金鑰  
 * @return  
 */    
public static AccessToken getAccessToken(String appid, String appsecret) {    
    AccessToken accessToken = null;    
    String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);    
    JSONObject jsonObject = httpRequest(requestUrl, "GET", null);    
    if (null != jsonObject) {    
        try {    
            accessToken = new AccessToken();    
            accessToken.setAccess_token(jsonObject.getString("access_token"));    
            accessToken.setExpires_in(jsonObject.getInt("expires_in"));    
        } catch (JSONException e) {    
            accessToken = null;    
            // 獲取token失敗    
            log.error("獲取token失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));    
        }    
    }    
    return accessToken;    
}