如何在底层连接有状态时使用Apache HttpClient?

我已经搜索了很多关于如何在multithreading中使用HttpClient的信息。 他们中的大多数建议使用ThreadSafeClientConnManager。 但我的应用程序必须登录一些主机(登录表单页面),以便HttpClient获得基础的有状态连接。 如果multithreading,ThreadSafeClientConnManager可以保持登录状态吗?

阅读本页的以下部分: 关于Cookie和状态管理的HttpClient教程 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); 

是的,HttpClient将使用线程安全连接管理器维护状态(例如会话cookie)。

如果您在登录时遇到任何问题,请尝试切换到“浏览器兼容性”Cookie政策。

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