Persistent Http client connections in java

2019-07-24 02:49发布

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 reuse 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 reuse it.

标签: java http
1条回答
手持菜刀,她持情操
2楼-- · 2019-07-24 03:10

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.

查看更多
登录 后发表回答