问题描述
你能告诉我如何将 jsessionid 存储在 cookie 中,以便它可以通过 post 请求传递给 servlet 吗?我使用的是 Apache HttpClient 4.0.3 版.我找到的所有解决方案都解释了如何使用 HttpClient 3.1 做到这一点.我已经阅读了教程并尝试了这个,但它不起作用.
Can you tell me how to store jsessionid in the 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 the 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);
编辑 - 进一步解释
我正在连接到朋友编写的 servlet.我已经登录并获得了 jsessionid
.现在我想发送另一个请求并且需要传递 jsessionid 以进行授权.Servlet 工作正常,因为我使用了 java HttpURLConnection,设置了 cookie,传递了它并且它工作了.现在使用 HttpClient 我没有任何异常,但是来自朋友的 servlet 的返回代码表明请求中没有 sessionid.
Edit - further explanations
I'm connecting to servlets written by a friend. I've logged in and obtained jsessionid
. Now I want to send another request and need to pass jsessionid for authorization purposes.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 a friend's servlet indicates that there was no sessionid in the request.
另一个编辑 - 我有一个解决方案我设置了请求标头的参数并且它起作用了.Servlet 识别 sessionid.httppost.setHeader("Cookie", "JSESSIONID="+ getSessionId());
Another Edit - I've got one solutionI set the parameter of request header and it worked. Servlet recognized sessionid.httppost.setHeader("Cookie", "JSESSIONID="+ getSessionId());
现在我的问题是:这个方法正确吗?
Now my question is: Is this method correct?
推荐答案
很高兴解决这个问题:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!