I am trying to figure out how to set and also retrieve cookies using HttpComponents, but I can’t find solid documentation, especially when it comes to setting cookies on the request. What I have seems to work, but at the same time I can’t confirm that the cookies I set are being sent correctly.
I notice that the cookie that I set on the request is also in the CookieStore after calling client.execute(), but I’m not sure if that’s just because I add it to the CookieStore before calling client.execute() (maybe it stays in the CookieStore without being actually sent with the request?). Is there a good way to confirm the cookie is sent?
HttpGet get = new HttpGet("http://example.com/");
DefaultHttpClient client = new DefaultHttpClient();
// set the cookies
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("foo", "bar");
cookie.setDomain("example.com");
cookie.setPath("/something/");
cookieStore.addCookie(cookie);
client.setCookieStore(cookieStore);
// get the cookies
HttpResponse response = client.execute(get);
List<Cookie> cookies = client.getCookieStore().getCookies();
just found the follwoing example which demonstrates the use of cookies in an login example: HttpComponents Example with Cookies
Maybe you can modify this in a way what the server responds with the content of the cookie sent, so you can eval if the cookie really was sent to the server. (You send cookie with “foo”, “bar” or some randomize values and the server will respond with “bar”, “foo” or something like that)