Persistent HTTP client connection in Java

I'm trying to write a simple Http client application in Java, and I'm a bit confused, apparently, in the different ways of establishing HTTP client connections and efficiently reusing objects.

Current I use the following steps (for simplicity, I excluded exception handling)

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(); } 

Regarding the above code, my questions are:

Assuming all URIs point to the same host (but different resources on that host). What is the recommended way to use one HTTP connection for all requests?

And how do you close the connection after the last request?

- edit: I am confused about why the above steps never use HttpURLConnection, I would suggest that client.execute() creates one, but since I never see it, I'm not sure how to close it or reuse it.

+1
source share
1 answer

To use persistent connection effectively, you need to use a unified 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 keep-alive connection is very difficult.

+5
source

Source: https://habr.com/ru/post/948580/


All Articles