微信开发之获取accessToken

public static String getToken(String apiurl, String appid, String secret)
     {
         String turl = String.format(
                 "%s?grant_type=client_credential&appid=%s&secret=%s", apiurl,
                appid, secret);
        HttpClient client = new DefaultHttpClient();
         HttpGet get = new HttpGet(turl);
        JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
         String result = null;
         try
         {
             HttpResponse res = client.execute(get);
             String responseContent = null; // 响应内容
             HttpEntity entity = res.getEntity();
             responseContent = EntityUtils.toString(entity, "UTF-8");
             JsonObject json = jsonparer.parse(responseContent)
                     .getAsJsonObject();
             // 将json字符串转换为json对象
             if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
             {
                 if (json.get("errcode") != null)
                 {// 错误时微信会返回错误码等信息,{"errcode":40013,"errmsg":"invalid appid"}
                 }
                 else
                 {// 正常情况下{"access_token":"ACCESS_TOKEN","expires_in":7200}
                     result = json.get("access_token").getAsString();
                 }
             }
         }
         catch (Exception e)
         {
             e.printStackTrace();
         }
         finally
         {
             // 关闭连接 ,释放资源
             client.getConnectionManager().shutdown();
             return result;
         }
     }

你可能感兴趣的:(微信)