Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HttpClient with multithreaded operation?

I've to do an application that performs a Login POST request in a certain host, then navigates some pages, finds and retrieves some data. Becase the website resouce is protected by session, so I have to login the website first before I can do some operation such as get or post some data. My question is because HttpClient is not thread-safe, how can I create only one HttpClient instance but threads can perform on it safely? Remember that the underlying connection must login first before it can be used to operate.

like image 803
wangyin Avatar asked Mar 28 '11 07:03

wangyin


People also ask

Is HttpClient multithreaded?

Concurrent execution of HTTP methods HttpClient is fully thread-safe when used with a thread-safe connection manager such as MultiThreadedHttpConnectionManager.

Is Java net HTTP HttpClient thread-safe?

Once created, an HttpClient instance is immutable, thus automatically thread-safe, and you can send multiple requests with it.

Is C# HttpClient thread-safe?

The HttpClient class was designed to be used concurrently. It's thread-safe and can handle multiple requests. You can fire off multiple requests from the same thread and await all of the responses, or fire off requests from multiple threads.

What is closeable HttpClient?

CloseableHttpClient is an abstract class that represents a base implementation of the HttpClient interface. However, it also implements the Closeable interface. Thus, we should close all its instances after use.


2 Answers

Here is an answer: http://pro-programmers.blogspot.com/2009/06/apache-httpclient-multi-threads.html

like image 74
nanda Avatar answered Oct 02 '22 23:10

nanda


You can make HttpClient thread safe by specifying a thread safe client manager.

API : http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/tsccm/ThreadSafeClientConnManager.html

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/DefaultHttpClient.html#DefaultHttpClient%28org.apache.http.conn.ClientConnectionManager%29

Example : http://thinkandroid.wordpress.com/2009/12/31/creating-an-http-client-example/

like image 33
Shamit Verma Avatar answered Oct 03 '22 00:10

Shamit Verma