欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpClient使用

程序员文章站 2022-06-24 22:26:08
...

案列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