views:

136

answers:

3

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

+1  A: 

I assume you use HttpClient 3.0. Try this,

  HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
ZZ Coder
So create a new client in each thread? or create 1 client for multiple threads?
MrThys
One client for all threads.
ZZ Coder
A: 

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.

amischiefr
+2  A: 

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);
Tim Büthe