Search code examples
javahttpurlconnectionsetcookie

Java Why aren't "Set-Cookie" headers being read?


I'm working on am application for a client. The website is https//www.seekingarrangement.com/login

When I use Chrome or Firefox, I see a response header for "Set-Cookie" with the a value of "laravel_session=eyJpdiI6InlXNkxTRzUxODRtR3BkT0xIR3ZDd0E9PSIsInZhbHVlIjoiMzlRaDdTSk1IRnNINjAyaWVvaGUrN25DYlJaRDVTNDVoMXBLWkdjaWNCN25Ldzg1UkVZazJ0c1JIVFhxODlMSytaRlk5Skd6Z0EyRG9XK29SUWhtOXc9PSIsIm1hYyI6ImFiNjdiYTczNDE4ZGMyOWViOTcxYTljZmUyNjhjY2ViM2E3N2ViMTBiMzBlYjA4MzgwZjhjOTVhNmVmMGM0OTMifQ%3D%3D; expires=Sat, 02-Apr-2016 04:19:15 GMT; Max-Age=82800; path=/; httponly

When I run the following code, however, the "Set-Cookie" values are empty.

private void onLoad() {
    CookieHandler.setDefault(new CookieManager());
    login();
}

private void login() {
    try {
       System.out.println("Logging in...");
       this.email = emailField.getText();
       this.password = passField.getText();

       /* 1.  connect to login url */  
       URL URL = new URL("https://www.seekingarrangement.com/login");
       HttpURLConnection conn = (HttpURLConnection) URL.openConnection();

       /* 2. GET response string */
       conn.setRequestMethod("GET");

       /* 3. Get Response cookies */
       Map cookiesTest = conn.getHeaderFields();
       String headerKeys[] = new String[cookiesTest.size()];
       String headerValues[] = new String[cookiesTest.size()];
       for(int i = 0;i<cookiesTest.size(); i++) {
           headerKeys[i] = conn.getHeaderFieldKey(i);
           headerValues[i] = conn.getHeaderField(i);
           System.out.println(i + ". " + headerKeys[i] + " : " + headerValues[i]);
       }

        // more code no relevant to my question
}

This leaves me with the following output tot the console:

Logging in...
0. null : HTTP/1.1 200 OK
1. Server : cloudflare-nginx
2. Date : Fri, 01 Apr 2016 05:37:35 GMT
3. Content-Type : text/html; charset=UTF-8
4. Transfer-Encoding : chunked
5. Connection : keep-alive
6. Set-Cookie : 
7. X-Powered-By : PHP/5.6.14
8. Cache-Control : no-cache
9. Set-Cookie : 

As you can see, both "Set-Cookie" response headers are blank. But If I check with any browser's developer tools, it shows actual values for "Set-Cookie"


Solution

  • If you remove the following line

    CookieHandler.setDefault(new CookieManager());
    

    it should show the Set-Cookie header in your sysout.

    Or if you use the CookieManager, you should be able to see the cookies stored in the CookieStore as below:

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

    and you can view the cookies in the cookie store:

    if(manager.getCookieStore().getCookies().size() > 0)
    {
        System.out.println("From cookieManager : " + manager.getCookieStore().getCookies());    
    }