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

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

问题描述

你能告诉我如何在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我没有得到任何异常,但朋友的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?

推荐答案

问题:

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 - 如何设置cookie with sessionID的POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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