HttpClient http GET连接

public void httpDoGet(String url, Map<String, Object> params) {

        //获取默认Client实例

        CloseableHttpClient client = HttpClients.createDefault();

        //拼接Get请求Url参数

        String apiUrl = url;

        StringBuffer sb =new StringBuffer();

        int i =0;

        for (String key : params.keySet()) {

            if (i ==0) {

                sb.append("?");

            } else {

                sb.append("&");

            }

            sb.append(key).append("=").append(params.get(key));

            i++;

    }

    apiUrl += sb;

    //创建HttpGet实例

    HttpGet httpGet =new HttpGet(apiUrl);

    //添加请求头信息

    httpGet.addHeader("Content-Type", "application/json;charset=utf-8");

    try {

        //获取响应的所有内容

        CloseableHttpResponse response = client.execute(httpGet);

        try {

            //获取响应消息体内容

            HttpEntity entity = response.getEntity();

            //转成String+防止乱码

            String result = EntityUtils.toString(entity, "UTF-8");

        } catch (Exception e) {

            response.close();

        }

    } catch (IOException e) {

    new RuntimeException(e);

    } finally {

        client.close();

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。