Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Cookies with HttpURLConnection in Java?

When I use HttpURLConnection and try con.getHeaderField("Set-Cookie") I get this response:

__cfduid=1111111aaaaaa; expires=Wed, 19-Dec-18 06:19:46 GMT; path=/; domain=.site.com; HttpOnly

But the browser cookies are:

__cfduid=1111111aaaaaa; _ym_uid=000000000; PHPSESSID=zzzzzzzz; _ym_isad=1; key=555

How I can get the FULL cookie, using HttpURLConnection? The most important cookie for me is key.

like image 731
Shannon Avatar asked Dec 19 '17 06:12

Shannon


1 Answers

The value of Set-cookie header modify or append new value to Cookies in browser. And browser delete expired cookie from cookies. The assembling work completed by browser.

When request web in java, programmer need assemble 'full' cookies by Set-cookie header in single or multi responses.

If you use HttpURLConnection, you can use CookieManager

This is an example

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);

URL url = new URL("https://stackoverflow.com");

URLConnection connection = url.openConnection();
connection.getContent();

List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
for (HttpCookie cookie : cookies) {
    System.out.println(cookie.getDomain());
    System.out.println(cookie);
}

When you send HTTP request, CookieManager will auto fill Cookie Header. And, the value can be directly achieved from CookieManger by domain.

like image 62
neuo Avatar answered Oct 28 '22 10:10

neuo