开发者

Does Apache HttpClient add the Cookies set by the java.net.CookieHandler to Request?

开发者 https://www.devze.com 2023-02-12 23:46 出处:网络
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

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


Is it that CookieHandler does not work with Apache HttpClient?

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号