wangyin
wangyin

Reputation: 121

How to use Apache HttpClient while the underlying connection is stateful?

I have googled a lot about how to use HttpClient with multithreading. Most of them suggest using the ThreadSafeClientConnManager. But my application has to login some host(a login form page) so that HttpClient obtains a underlying stateful connection. Can ThreadSafeClientConnManager hold the login state if multithreading?

Upvotes: 2

Views: 3822

Answers (2)

Shamit Verma
Shamit Verma

Reputation: 3827

Yes, HttpClient will maintain state (E.g. session cookies) with thread safe connection manager.

If you face any issues with login, try switching to "Browser compatibility" cookie policy.

client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

Upvotes: 0

Hosane
Hosane

Reputation: 915

Read the following sections from this page: HttpClient Tutorial about Cookies and state management 3.8. HTTP state management and execution context 3.9. Per user / thread state management

and this maybe that code you want:

HttpClient httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/"); 
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);

Upvotes: 1

Related Questions