本文介绍了如何在 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 包中的 session/cookies 设置?
Is there a better way to manage the session/cookies setting in the HttpClient package?
推荐答案
正确的做法是准备一个CookieStore
需要在 HttpContext
依次传递给每个 HttpClient#execute()
调用.
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 中处理会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!