简体   繁体   中英

Connection to same URL in different threads using HttpClient

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

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

I assume you use HttpClient 3.0. Try this,

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM