CloseableHttpClient 进行post,get请求

7,255 阅读2分钟

这是我参与更文挑战的第 6 天,活动详情查看

1.加载依赖

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>

2.为啥选择CloseableHttpClient,而没有选择httpClient?
           httpclient是一个线程安全的类,没有必要由每个线程在每次使用时创建,全局保留一个即可. HttpClient每次用完就关闭,每次new\close的流程对JVM的内存消耗很大,这个时候需要引入连接池,我们可以看下ClosableHttpClient;
           ClosableHttpClient默认会创建一个大小为5的连接池(针对RPC调用不频繁的情况),端到端的链接可以复用,配置evict相关的两个方法,一方面用于处理类似CLOSE_WAIT状态的异常链接,一方面用于处理IDLE状态的链接,其内部源码会开启一个定时任务去检测
           CloseableHttpClient实现了Closeable接口,可以自动关闭资源,不需要在手动关闭资源了

3.发送GET和POST请求的步骤如下:

  1. 使用帮助类HttpClients创建CloseableHttpClient对象.
  2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.
  3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
  4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进HttpPost实体.
  5. 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例
  6. 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
  7. 最后关闭HttpClient资源. 直接上代码:
//发送post请求
    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            if (param != null) {
                List<BasicNameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();//获取返回状态值
            if (status == HttpStatus.SC_OK) {//请求成功
                HttpEntity httpEntity = response.getEntity();
                if(httpEntity != null) {
                    resultString = EntityUtils.toString(httpEntity, "utf-8");
                    EntityUtils.consume(httpEntity);//关闭资源
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(resultString);
        return resultString;
    }

    //发送get请求
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            URIBuilder uri = new URIBuilder(url);
            //get请求带参数
            List<NameValuePair> list = new LinkedList<>();
            if (param != null) {
                List<BasicNameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    BasicNameValuePair param1 = new BasicNameValuePair(key, param.get(key));
                    list.add(param1);
                }
            }
            uri.setParameters(list);
            // 创建Http Post请求
            HttpGet httpGet = new HttpGet(uri.build());
            //设置请求状态参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(3000)
                    .setSocketTimeout(3000)
                    .setConnectTimeout(3000).build();
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            // 执行http请求
            response = httpClient.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();//获取返回状态值
            if (status == HttpStatus.SC_OK) {//请求成功
                HttpEntity httpEntity = response.getEntity();
                if(httpEntity != null) {
                    resultString = EntityUtils.toString(httpEntity, "utf-8");
                    EntityUtils.consume(httpEntity);//关闭资源
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(resultString);
        return resultString;
    }