2011-03-28 21 views
2

我已經搜索了很多關於如何在多線程中使用HttpClient的問題。大多數人建議使用ThreadSafeClientConnManager。 但我的應用程序必須登錄某個主機(登錄表單頁面),以便HttpClient獲得基礎狀態連接。 如果多線程,ThreadSafeClientConnManager是否可以保持登錄狀態?如何在底層連接有狀態時使用Apache HttpClient?

+0

服務器是否使用會話ID的Cookie? 「有狀態連接」與HTTP的含義是什麼? – Ramon 2011-03-28 08:09:13

回答

0

是的,HttpClient將維護線程安全連接管理器的狀態(例如會話cookie)。

如果您在登錄時遇到任何問題,請嘗試切換到「瀏覽器兼容性」Cookie政策。

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

Grate help,謝謝Shamit。它的工作really.btw哪個文件解釋這個功能? – wangyin 2011-03-28 13:05:49

+0

文檔:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html – 2011-03-28 13:42:11

1

從這個頁面閱讀以下部分:HttpClient Tutorial about Cookies and state management 3.8。 HTTP狀態管理和執行上下文 3.9。每用戶/線程狀態管理

,這也許就是代碼你想要的:

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); 
相關問題