Question

What is the correct method to get the content of an URL in multiple threads using HttpClient in java?

For example loading a List with items, loading each item in a different thread at the same time and getting the information from the same URL with different parameters.

In a application I am creating it gives me no element found exception when reading XML from the same URL in different threads..

Was it helpful?

Solution

I assume you use HttpClient 3.0. Try this,

  HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());

OTHER TIPS

Because the accepted answer descirbes a solutuion for HttpClient 3.x only, and the current version is 4.1 (This is also included in Android), I would like to share a working 4.x example. Maybe that saves someone some hustle.

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

HttpParams parameters = new BasicHttpParams();
ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(parameters, schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(connectionManager, parameters);

ThreadSafeClientConnManager also depricated in 4.2. Instead of use org.apache.http.impl.conn.PoolingHttpClientConnectionManager

If you place the data into application scope it should be available from any thread. You shouldn't use this if the data is sensitive, and remember to explicitly remove it when you are done with it, as it exists through the life of the server if not removed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top