CloseableHttpResponse response = null;
try {
// do some thing ....
HttpPost request = new HttpPost("some url");
response = getHttpClient().execute(request);
// do some other thing ....
} catch(Exception e) {
// deal with exception
} finally {
if(response != null) {
try {
response.close(); // (1)
} catch(Exception e) {}
request.releaseConnection(); // (2)
}
}
I've made a http request like above.
In order to release the underlying connection, is it correct to call (1) and (2)? and what's the difference between the two invocation?
CloseableHttpResponse.close()
closes the tcp socketHttpPost.releaseConnection()
closes the tcp socketEntityUtils.consume(response.getEntity())
allows you to re-use the tcp socketDetails
CloseableHttpResponse.close()
closes the tcp socket, preventing the connection from being re-used. You need to establish a new tcp connection in order to initiate another request.This is the call chain that lead me to the above conclusion:
HttpPost.releaseConnection()
also closes the Socket. This is the call chain that lead me to the above conclusion:Here is experimental code that also demonstrates the above three facts:
pom.xml
Output:
Notice that both
.close()
and.releaseConnection()
both result in a new tcp connection. Only consuming the entity allows you to re-use the tcp connection.If you want the connect to be re-usable after each request, then you need to do what @Matt recommended and consume the entity.