微信根據 AppId 和 appSecret 獲取全局AccessToken

   private static final Logger LOGGER = Logger.getLogger(XXX.class);


    /**
     * 獲access_token
     *
     * @return
     */
    public static String getAccessToken(String appId,String appSecret) {

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appId + "&secret=" + appSecret;

        LOGGER.info("request user info from url: {" + url + "}");
        JsonObject accessTokenInfo = null;
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            //LOGGER.error("獲取Token-------------------"+response);
            Gson token_gson = new Gson();

            accessTokenInfo = token_gson.fromJson(response, JsonObject.class);
            LOGGER.info("get accessTokenInfo success. [result={" + accessTokenInfo + "}]");

            return accessTokenInfo.get("access_token").toString().replaceAll("\"", "");

        } catch (Exception ex) {
            LOGGER.error("fail to request wechat user info. [error={" + ex + "}]");
        }
        return "";
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章