简体   繁体   English

基础连接为有状态时如何使用Apache HttpClient?

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

I have googled a lot about how to use HttpClient with multithreading. 我在Google上搜索了很多有关如何在多线程中使用HttpClient的信息。 Most of them suggest using the ThreadSafeClientConnManager. 他们中的大多数建议使用ThreadSafeClientConnManager。 But my application has to login some host(a login form page) so that HttpClient obtains a underlying stateful connection. 但是我的应用程序必须登录某个主机(登录表单页面),以便HttpClient获得基础的有状态连接。 Can ThreadSafeClientConnManager hold the login state if multithreading? 如果是多线程,ThreadSafeClientConnManager是否可以保留登录状态?

Read the following sections from this page: HttpClient Tutorial about Cookies and state management 3.8. 阅读此页面的以下部分: 关于Cookie和状态管理 3.8的HttpClient教程 HTTP state management and execution context 3.9. HTTP状态管理和执行上下文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);

Yes, HttpClient will maintain state (Eg session cookies) with thread safe connection manager. 是的,HttpClient将使用线程安全连接管理器维护状态(例如会话cookie)。

If you face any issues with login, try switching to "Browser compatibility" cookie policy. 如果登录时遇到任何问题,请尝试切换到“浏览器兼容性” cookie策略。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM