How to use HttpClient with multithreaded operation?

19,858

Solution 1

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

Solution 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/

Share:
19,858

Related videos on Youtube

wangyin
Author by

wangyin

Updated on June 04, 2022

Comments

  • wangyin
    wangyin almost 2 years

    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.

  • wangyin
    wangyin about 13 years
    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?
  • wangyin
    wangyin about 13 years
    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?
  • Shamit Verma
    Shamit Verma about 13 years
    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.
  • wangyin
    wangyin about 13 years
    OK,Thanks very muck!I will try again.
  • Eyal
    Eyal over 11 years
    Keep in mind that ThreadSafeClientConnManager is deprecated as of version 4.2 Use PoolingClientConnectionManager instead.
  • Abdull
    Abdull about 11 years
    See stackoverflow.com/a/14762579/923560 for an example on how to set up a PoolingClientConnectionManager as of version 4.2
  • Sergey
    Sergey over 10 years

Related