My simple Apache HttpClient (4.0.1) client application makes an HttpGet request to a server URL in the main() method and prints the response. On startup, the application registers an implementation of java.net.CookieHandler in a static block.
On checking the cookies received on the server side, I found that the cookies are not being received by the Server when the HttpClient makes the GET request.
On the other hand, when I replaced the Apache HttpClient with a plain java.net.URL(HTTP_URL).openStream(), the cookies were set by the CookieHandler on the Request and were received by the Server.
Is it that CookieHandler does not work with Apache HttpClient?
Code:
Client.java
static { CookieHandler.setDefault(new CookieHandler() { public Map get(URI u, List r) { return Collections.singletonMap("Cookie", Collections.singletonList(COOKIE_STRING)); } }); }
Using HttpClient (does not put cookies on request)
HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(HTTP_URL); client.execute(get);
Using java.net.URL (sets the cookies on request)
URL url = new URL(HTTP_URL); InputStream is = url.openStream();
That is correct.
The Apache HttpClient codebase uses its own cookie and cookie store representations / mechanisms. Here is a link to the relevant section of the HttpClient tutorial. (It is pretty sketchy, but if you look at the javadocs for the relevant classes, you should be able to figure out how to use it.)
(If you are using an older version of Apache HttpClient, beware that the APIs have changed significantly.)