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.
Concurrent execution of HTTP methods HttpClient is fully thread-safe when used with a thread-safe connection manager such as MultiThreadedHttpConnectionManager.
Once created, an HttpClient instance is immutable, thus automatically thread-safe, and you can send multiple requests with it.
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.
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.
Here is an answer: http://pro-programmers.blogspot.com/2009/06/apache-httpclient-multi-threads.html
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With