如何处理HttpClient 4.1中的会话 [英] How to Handle the Session in HttpClient 4.1

查看:147
本文介绍了如何处理HttpClient 4.1中的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用HttpClient 4.1.1来测试我的服务器的REST API。

I am using the HttpClient 4.1.1 to test my server's REST API.

我可以管理登录似乎工作正常,但当我尝试做任何其他我失败了。

I can manage to login seem to work fine but when I try to do anything else I am failing.

很可能我在下一个请求中设置了Cookie。

Most likely I have a problem setting the cookie in the next request.

我的代码目前:

HttpGet httpGet = new HttpGet(<my server login URL>);
httpResponse = httpClient.execute(httpGet)
sessionID = httpResponse.getFirstHeader("Set-Cookie").getValue();
httpGet.addHeader("Cookie", sessionID);
httpClient.execute(httpGet);

有没有更好的方法来管理HttpClient包中的session / cookies设置?

Is there a better way to manage the session/cookies setting in the HttpClient package?

推荐答案

正确的方法是准备 CookieStore ,您需要在 HttpContext ,您随后会传送每个 HttpClient#execute() call。

The correct way is to prepare a CookieStore which you need to set in the HttpContext which you in turn pass on every HttpClient#execute() call.

HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// ...

HttpResponse response1 = httpClient.execute(method1, httpContext);
// ...

HttpResponse response2 = httpClient.execute(method2, httpContext);
// ...

这篇关于如何处理HttpClient 4.1中的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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