美文网首页
HttpClient使用

HttpClient使用

作者: jswel520 | 来源:发表于2018-11-04 13:54 被阅读0次

案列1:获取token

    /**
     * 获取token.
     * @param requestUrl 请求地址
     * @param accessKey accessKey
     * @return token字符串
     */
    public static String getToken(String requestUrl, String accessKey) {
        //token信息
        String access_token = null;
        String charset = "utf-8";
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();

            HttpGet httpGet = new HttpGet(requestUrl);
            httpGet.setHeader("Access-Key", accessKey);
            HttpResponse response = httpClient.execute(httpGet);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String result = EntityUtils.toString(resEntity, charset);
                    JSONObject jsonbody = JSONObject.parseObject(result);
                    access_token = ((String) jsonbody.get("access_token"));
                }
            }
        } catch (Exception e) {
            LOGGER.error("获取Token失败", e);
        }
        return access_token;
    }

相关文章

网友评论

      本文标题:HttpClient使用

      本文链接:https://www.haomeiwen.com/subject/qlbrxqtx.html