10

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.

Steinar
  • 149
  • 1
  • 16
Shannon
  • 101
  • 1
  • 1
  • 4
  • Note, if con.getHeaderField(name) is called on a connection that sets the same header multiple times with possibly different values (which may be the case for 'set-cookie'), only the last value is returned. So better you iterate through all headers fields and test each field for the name 'Set-Cookie'. – Ralph Sep 07 '22 at 08:52

1 Answers1

6

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.

neuo
  • 653
  • 4
  • 10
  • 1
    And how to do it? Can a small example? We have one HeaderField("Set-Cookie"), and I need full cookies. – Shannon Dec 19 '17 at 16:36
  • @Shannon the answer here shows how to set cookies: https://stackoverflow.com/questions/10814462/how-to-get-cookies-in-httpurlconnection-by-using-cookiestore – Josh Apr 23 '20 at 09:51
  • did not work for me, but it did using the Apache HttpClient library: https://stackoverflow.com/a/28973623/1915920 – Andreas Covidiot Jun 23 '20 at 09:48