Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

hitan picture hitan · Nov 12, 2010 · Viewed 99.7k times · Source

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

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.

Another Edit - I've got one solution I 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?

Answer

Keith Lee picture Keith Lee · Oct 11, 2011

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

So Easy!