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?
Short answer:
request.releaseConnection()is releasing the underlying HTTP connection to allow it to be reused.response.close()is closing a stream (not a connection), this stream is the response content we are streaming from the network socket.Long Answer:
The correct pattern to follow in any recent version > 4.2 and probably even before that, is not to use
releaseConnection.request.releaseConnection()releases the underlying httpConnection so the request can be reused, however the Java doc says:Instead of releasing the connection, we ensure the response content is fully consumed which in turn ensures the connection is released and ready for reuse. A short example is shown below: