美文网首页软件测试学习之路
Java学习笔记 32 - 使用httpClient4.5创建连

Java学习笔记 32 - 使用httpClient4.5创建连

作者: 乘风破浪的姐姐 | 来源:发表于2018-11-21 17:51 被阅读156次
    一、为什么要用Http连接池

    1、降低连接时间的消耗:两个主机建立连接的过程中涉及到多个数据包的交换,Http连接需要的三次握手,http连接的关闭需要四次挥手,使用传统的HttpURLConnection,每次发起Http请求都会重新建立TCP连接,用完就会关闭连接。如果采用连接池则减少了这部分时间损耗。

    2、支持更大的并发:如果不采用连接池,每次连接都会打开一个端口,在大并发的情况下系统的端口资源很快就会被用完,导致无法建立新的连接。

    二、使用httpClient4.5创建连接池

    导入包

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

    1、创建连接池步骤
    创建连接池
    setMaxTotal设置连接池最大并发连接数
    setDefaultMaxPerRoute设置单路由最大并发数
    setConnectTimeout使用连接池来管理连接,设置建立连接最大时间
    setSocketTimeout设置数据传输过程中数据包之间间隔的最大时间
    setProxy设置连接代理(根据需要)

    private static CloseableHttpClient httpclient;
        static {
            PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
            manager.setMaxTotal(200); //连接池最大并发连接数
            manager.setDefaultMaxPerRoute(200);//单路由最大并发数,路由是对maxTotal的细分
            httpclient = HttpClients.custom().setConnectionManager(manager).build();
        }
    
        private static RequestConfig config =RequestConfig.copy(RequestConfig.DEFAULT)
                .setSocketTimeout(10000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(100).build();
               // .setProxy(new HttpHost("127.0.0.1",8888,"http")).build();
    
    三、使用连接池处理Get请求
    public static String doGet(String url, Map<String, Object> header)
                throws HttpClientException {
            String ret = "";
            HttpGet get = new HttpGet(url);
            get.setConfig(config);
            get.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
            CloseableHttpResponse closeableHttpResponse = null;
            try {
                if (header != null) {
                    for (Map.Entry<String, Object> entry : header.entrySet()) {
                        get.setHeader(entry.getKey(), entry.getValue().toString());
                    }
                }
                closeableHttpResponse = httpclient.execute(get);
                if (closeableHttpResponse.getStatusLine().getStatusCode() == 200) {
                    ret = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
                } else {
                    throw new HttpClientException(
                            "System level error, Code=[" + closeableHttpResponse.getStatusLine().getStatusCode() + "].");
                }
            } catch (ClientProtocolException e) {
                throw new HttpClientException("HttpClient error," + e.getMessage());
            } catch (IOException e) {
                throw new HttpClientException("IO error," + e.getMessage());
            } finally {
                if (closeableHttpResponse != null) {
                    try {
                        closeableHttpResponse.close();
                    } catch (IOException e) {
                    }
                }
            }
            return ret;
        }
    
    四、使用连接池处理Post请求
     public static String doPost(String url, Map<String, Object> params, Map<String, Object> header)
                throws HttpClientException {
            String ret = "";
            HttpPost post = new HttpPost(url);
            post.setConfig(config);
            post.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
            CloseableHttpResponse closeableHttpResponse = null;
            HttpEntity postEntity = null;
            try {
                if(params!=null) {
                    List<NameValuePair> list = new ArrayList<NameValuePair>();
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                    }
                    postEntity = new UrlEncodedFormEntity(list);
                    post.setEntity(postEntity);
                }
    
                if (header != null) {
                    for (Map.Entry<String, Object> entry : header.entrySet()) {
                        post.setHeader(entry.getKey(), entry.getValue().toString());
                    }
                }
                closeableHttpResponse = httpclient.execute(post);
                if (closeableHttpResponse.getStatusLine().getStatusCode() == 200) {
                    ret = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
                } else {
                    throw new HttpClientException(
                            "System level error, Code=[" + closeableHttpResponse.getStatusLine().getStatusCode() + "].");
                }
            } catch (ClientProtocolException e) {
                throw new HttpClientException("HttpClient error," + e.getMessage());
            } catch (IOException e) {
                throw new HttpClientException("IO error," + e.getMessage());
            } finally {
                if(postEntity!=null) {
                    try {
                        EntityUtils.consume(postEntity);
                    } catch (IOException e) {
                    }
                }
                if (closeableHttpResponse != null) {
                    try {
                        closeableHttpResponse.close();
                    } catch (IOException e) {
                    }
                }
            }
            return ret;
        }
    
    五、应用测试
     public static void main(String[] args) {
            String result = null;
            String url ="http://api.superepc.com/vtm/DataFunc?grant_code=XF9JKY0R&is_car_config=0&isCN=1&vinCode=LGBG22E22AY081092";
            try {
             result = doGet("http://123.58.251.183:8080/goods/UserServlet?method=loginMobile&loginname=test1&loginpass=test1");
               String  result1 = doGet(url);
               System.out.println(result);
            } catch (HttpClientException e) {
                e.printStackTrace();
            }
    
    
        Map<String,Object> params = new HashMap<String,Object>();
            params.put("method", "loginMobile");
            params.put("loginname", "test1");
            params.put("loginpass", "test1");
    
            try {
                result = doPost("http://123.58.251.183:8080/goods/UserServlet", params);
            } catch (HttpClientException e) {
                e.printStackTrace();
            }
          System.out.println(result);
    }
    

    相关文章

      网友评论

        本文标题:Java学习笔记 32 - 使用httpClient4.5创建连

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