tags:

views:

81

answers:

1

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 content = entity.getContent();
   processStream (content );
   content.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: I am confused at why the above steps never use HttpURLConnection, I would assume client.execute() creates one, but since I never see it I am not sure how to close it or re-use it.

+4  A: 

To make use of persistent connection efficiently, you need to use the pooled connection manager,

SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
        new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);

My biggest problem with HttpURLConnection is its support for persistent connection (keep-alive) is very buggy.

ZZ Coder
Thanks for the info, for anyone interested the official documentation for this is (see 2.8.4. Pooling connection manager) http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/pdf/httpclient-tutorial.pdf
Akusete