开发者

How to Handle the Session in Apache HttpClient 4.1

开发者 https://www.devze.com 2023-03-10 22:39 出处:网络
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.

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.

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

Here is my code currently:

HttpGet httpGet = new HttpGet(<my server login URL>);
httpResponse = httpClient.execute(httpGet)
sessionID = httpResponse.getFirstHeader("Se开发者_高级运维t-Cookie").getValue();
httpGet.addHeader("Cookie", sessionID);
httpClient.execute(httpGet);

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号