Persistant Http client connections in java
Posted
by Akusete
on Stack Overflow
See other posts from Stack Overflow
or by Akusete
Published on 2010-05-24T01:02:56Z
Indexed on
2010/05/24
1:11 UTC
Read the original article
Hit count: 289
I am trying to write a simple Http client application in Java and am a bit confused by the seemingly different ways to establish Http client connections, and efficiently re-use the objects.
Current I am using the following steps (I have left out exception handling for simplicity)
Iterator<URI> uriIterator = someURIs();
HttpClient client = new DefaultHttpClient();
while (uriIterator.hasNext()) {
URI uri = uriIterator.next();
HttpGet request = new HttpGet(uri);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream s = entity.getContent();
processStream ();
s.close();
}
In regard to the code above, my questions is:
Assuming all URI's are pointing to the same host (but different resources on that host). What is the recommended way to use a single http connection for all requests?
And how do you close the connection after the last request?
--edit: Also what is the difference between using uri.openConnection(), versus HttpClient? Which is preferable, and what other methods exist?
© Stack Overflow or respective owner