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

查看:76
本文介绍了如何在Apache 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程序包中的会话/cookie设置?

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

推荐答案

正确的方法是准备

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

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

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