Reputation: 15044
Is it a bad practice to re-use a single HTTPClient instance for every request? I make a request
to get data from yahoo webservice
, now in another page I make a webservice
call to google.
Can I use the same HTTPClient instance in these two different pages or should I create new HTTPClient object for both?
Upvotes: 1
Views: 1893
Reputation: 340883
You should definitely reuse them and treat HttpClient
as a singleton. Having single instances reused across the whole application makes it possible to take advantage of keep-alive connections and persist cookies between calls.
Quoting the official documentation for 3.x:
Generally it is recommended to have a single instance of HttpClient per communication component or even per application. However, if the application makes use of HttpClient only very infrequently, and keeping an idle instance of HttpClient in memory is not warranted, it is highly recommended to explicitly shut down the multithreaded connection manager prior to disposing the HttpClient instance. This will ensure proper closure of all HTTP connections in the connection pool.
The same applies to 4.x, just make sure to use PoolingClientConnectionManager
.
Upvotes: 7