响应实体变为空时,Apache PoolingHttpClientConnection Manager释放连接

时间:2016-12-25 18:43:35

标签: java web-services apache-httpclient-4.x

我正在使用Apache PoolingHttpClientConnectionManagerClosableHttpClientCloseableHttpResponse一起汇集连接以进行服务调用。要阅读服务器响应,我正在使用EntityUtils.consume(httpResponse.getEntity())。我想知道在httpResponse成为null时如何释放连接。我尝试了releaseConnection()PoolingHttpClientConnectionManager的方法),但它不起作用。你可以在下面找到代码。

    String decision = "";

    CloseableHttpResponse httpResponse = null;
    try {
        HttpPost requestPost = new HttpPost(endpoint1);                                         requestPost.setHeader("Connection", "close");

        requestPost.setHeader("Content-type",
                "application/x-www-form-urlencoded");
        requestPost.addHeader("Accept-Encoding", "gzip,deflate");
        String xmlRequestStr = "Request=" + URLEncoder.encode(urlString);
        String soRequest = xmlRequestStr;
        requestPost.setEntity(new StringEntity(soRequest));
        httpResponse = client.execute(requestPost);
        decision = EntityUtils.toString(httpResponse.getEntity(),encod);
        //connEvictor.shutdown();
    } catch (Exception e) {
        System.out.println("Pooling Connection manager Exception : " + e.getMessage());
        e.printStackTrace();
        //connEvictor.shutdown();
        throw new ToolkitException("Connection Manager Exception", e.getMessage());
    } finally {
        EntityUtils.consume(httpResponse.getEntity());
        httpResponse.close();
    }

1 个答案:

答案 0 :(得分:0)

CloseableHttpClient不应返回null响应。关于错误应引发异常,因此可以安全地调用close()。见documentation

请勿在{{1​​}}子句中调用EntityUtils.consume(httpResponse.getEntity());,因为如果发生错误,则不会执行finally方法

请阅读http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html中的连接驱逐策略,您可以实施监视器以关闭已在服务器上阻止或关闭的过期和空闲连接。监视器调用closecloseExpiredConnections()