如何在底层连接有状态时使用Apache HttpClient? [英] How to use Apache HttpClient while the underlying connection is stateful?

查看:134
本文介绍了如何在底层连接有状态时使用Apache HttpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

从这个页面阅读以下部分:关于Cookie和状态管理的HttpClient教程
3.8。 HTTP状态管理和执行上下文
3.9。每用户/线程状态管理

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);

这篇关于如何在底层连接有状态时使用Apache HttpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆