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.
Asked
Active
Viewed 2.0k times
2 Answers
3

nanda
- 24,458
- 13
- 71
- 90
-
1I have read it but it's not what I want.In the post you suggest the version of HttpClient is 3.x. What I use is 4.x and I need a stateful connection before it can be used, not stateless.if stateless ThreadSafeClientConnManager is suggest, but what if stateful is required? – wangyin Mar 28 '11 at 07:13
-
good article http://progrnotes.blogspot.com/2013/10/use-httpclient-in-multithreaded.html – Sergey Oct 10 '13 at 07:36
2
You can make HttpClient thread safe by specifying a thread safe client manager.
Example : http://thinkandroid.wordpress.com/2009/12/31/creating-an-http-client-example/

Shamit Verma
- 3,839
- 23
- 22
-
yes I can. as far as I know, the single connection is used by HttpClient. If I use ThreadSafeClientConnManager, can it hold my first login session? – wangyin Mar 28 '11 at 07:21
-
Yes, state is independent of connection. E.g. if request 1 sets a cookie, it would be visible to request 2 (for the same domain) with Thread Safe Conn manger as well. – Shamit Verma Mar 28 '11 at 07:55
-
-
3Keep in mind that ThreadSafeClientConnManager is deprecated as of version 4.2 Use [PoolingClientConnectionManager](http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/PoolingClientConnectionManager.html) instead. – Eyal Dec 05 '12 at 15:04
-
See http://stackoverflow.com/a/14762579/923560 for an example on how to set up a `PoolingClientConnectionManager` as of version 4.2 – Abdull Feb 07 '13 at 22:53