Apache PoolingHttpClientConnection Manager Release Connection when Response Entity becomes null

678 Views Asked by At

I am using Apache PoolingHttpClientConnectionManager to pool the connections along with ClosableHttpClient and CloseableHttpResponse to make the service call. To read the sever response I am using EntityUtils.consume(httpResponse.getEntity()). I would like to know how to release the connection when httpResponse becomes null. I have tried releaseConnection() (method of PoolingHttpClientConnectionManager) but it is not working. You can find the code below.

    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

There are 1 best solutions below

11
On

CloseableHttpClient should not return a null response. On errors should raise an exception, so its safe to call close(). See documentation

Do not call EntityUtils.consume(httpResponse.getEntity()); in finally clause because if error occurs the close method won't be executed

Please read connection eviction policy in http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html you can implement a monitor to close expired and idle connections that have been blocked or closed on server. The monitor calls closeExpiredConnections() and closeIdleConnections(period