45

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

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。

另一个编辑 - 我有一个解决方案 ,我设置了请求标头的参数并且它有效。Servlet 识别出 sessionid。
httppost.setHeader("Cookie", "JSESSIONID="+ getSessionId());

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

4

4 回答 4

43

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

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

太简单!

于 2011-10-11T07:20:00.740 回答
23

我通过 HttpContext 传递 cookie 来做到这一点:

HttpContext localContext = new BasicHttpContext();

localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

response = client.execute(httppost, localContext);
于 2011-02-24T23:34:14.917 回答
11
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
response = client.execute(httppost, localContext);

没有在 4.5 版本中不起作用

cookie.setDomain(".domain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
于 2015-12-21T13:09:14.323 回答
2

您可能应该设置所有 cookie 属性,而不仅仅是它的值。setPath(), setDomain()... 等

于 2015-12-16T23:02:08.697 回答