10

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I 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?
2

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/

5 Comments

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?
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.
OK,Thanks very muck!I will try again.
Keep in mind that ThreadSafeClientConnManager is deprecated as of version 4.2 Use PoolingClientConnectionManager instead.
See stackoverflow.com/a/14762579/923560 for an example on how to set up a PoolingClientConnectionManager as of version 4.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.