Apache HttpClient 4.0.3 - 如何为POST请求设置带sessionID的cookie? [英] Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

查看:544
本文介绍了Apache HttpClient 4.0.3 - 如何为POST请求设置带sessionID的cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我如何在cookie中存储jsessionid,所以它可以通过post请求传递给servlet吗?我正在使用Apache HttpClient版本4.0.3。
我发现的所有解决方案都解释了如何使用HttpClient 3.1执行此操作。
我已经阅读了教程并尝试了这个,但它无法正常工作。

can you tell me how to store jsessionid in cookie, so it can be passed to the servlet with post request? I'm using Apache HttpClient version 4.0.3. All the solutions I've found explains how to do this with HttpClient 3.1. I've read tutorial and tried this, but it isn't working.

HttpPost httppost = new HttpPost(postData);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", getSessionId());
cookieStore.addCookie(cookie);
client.setCookieStore(cookieStore);
response = client.execute(httppost);

编辑 - 进一步说明

我' m连接到朋友写的servlet。我已登录并获得 jsessionid 。现在我想发送另一个请求,需要通过jsessionid进行授权。
Servlet运行正常,因为我使用了Java HttpURLConnection,设置了cookie,传递了它并且它有效。现在使用HttpClient我没有异常但是来自friend的servlet的返回代码表明请求中没有sessionid。

Edit - further explanations
I'm connecting to servlets written by friend. I've logged in and obtained jsessionid. Now I want to send another request and need to pass jsessionid for authorization purpose. Servlet works fine because I used java HttpURLConnection, set the cookie, passed it and it worked. Now with HttpClient I get no exceptions but the return code from friend's servlet indicates that there was no sessionid in the request.

另一个编辑 - 我有一个解决方案
我设置了请求标头的参数并且它有效。 Servlet识别的sessionid。

httppost.setHeader(Cookie,JSESSIONID =+ getSessionId());

现在我的问题是:这种方法是否正确?

Now my question is: Is this method correct?

推荐答案

我很高兴解决这个问题问题:

I am so glad to solve this problem:

HttpPost httppost = new HttpPost(postData); 
CookieStore cookieStore = new BasicCookieStore(); 
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", getSessionId());

//cookie.setDomain("your domain");
cookie.setPath("/");

cookieStore.addCookie(cookie); 
client.setCookieStore(cookieStore); 
response = client.execute(httppost); 

如此简单!

这篇关于Apache HttpClient 4.0.3 - 如何为POST请求设置带sessionID的cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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