29

I have a Java application (JDK 1.7.0_13) and am using java.net.HttpURLConnection to connect to some servlet based services that do session management. I am trying to figure out how to use java.net.CookieManager to track session cookies. Reading the docs I get the impression that installing CookieManager with CookieHandler.setDefault(new CookieManager()) should cause cookie management to happen automatically. However, multiple requests to the same URL's does not seem to preserve cookies. Do I have to manually extract cookies from responses and resend them in requests on my own or is CookieManager going to do this for me automatically? If CookieManager doesn't, then what value does it add?

To test things, I have a servlet that successfully increments a counter each time my browser visits a URL. This works fine from Safari, FireFox, and Chrome... However, I can't get it to work from a standalone Java application.

Here's a very simple test program to illustrate what I was hoping would simple work. It installs the CookieManager at the start and then calls a fetch(String urlString) method repeatedly as URLs are typed in at the console.

package com.brilliant.experimental;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpFetcher {  
    public static void fetch(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            int status = conn.getResponseCode();
            System.out.println("Status = " + status);
            String key;
            System.out.println("Headers-------start-----");
            for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++) {
                System.out.println(key + ":" + conn.getHeaderField(i));
            }
            System.out.println("Headers-------end-----");
            System.out.println("Content-------start-----");
            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                System.out.println(inputLine);
            }
            System.out.println("Content-------end-----");
            in.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        CookieHandler.setDefault(new CookieManager());

        for (int i = 0; i < args.length; i++) {
            fetch(args[i]);
        }

        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader reader = new BufferedReader(isr);
        String prompt = "> ";
        String urlString;
        try {
            for (System.out.print(prompt);
                    (urlString = reader.readLine()) != null; 
                    System.out.print(prompt)) 
            {
                fetch(urlString);
            }
        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }

}

Invoking my servlet from this app clearly gets a session cookie back from the server. However, invoking again gets a new session cookie.

> http://localhost:8080/brilliant/TestServlet
Status = 200
Headers-------start-----
Server:Resin/4.0.34
Cache-Control:private
Set-Cookie:JSESSIONID=aaaMp0uKke4gp9_-nUuZt; path=/
Content-Length:19
Date:Wed, 13 Feb 2013 18:02:31 GMT
Headers-------end-----
Content-------start-----
Session count is 0
Content-------end-----
> http://localhost:8080/brilliant/TestServlet
Status = 200
Headers-------start-----
Server:Resin/4.0.34
Cache-Control:private
Set-Cookie:JSESSIONID=aaaZ-oPaC1I9WdEDoUuZt; path=/
Content-Length:19
Date:Wed, 13 Feb 2013 18:02:33 GMT
Headers-------end-----
Content-------start-----
Session count is 0
Content-------end-----

So, to summarize, do I have to do something else to make CookieManager work automatically for me, or do I have to resort to manually extracting cookies from responses and resending them with requests?

Chuck
  • 1,788
  • 2
  • 15
  • 28
  • please move to http://stackoverflow.com/questions/12349266/how-do-i-persist-cookies-when-using-httpurlconnection/32001630#32001630。 the best solution has came up。 – hgg Aug 14 '15 at 03:14

1 Answers1

63

I run your code and replace this

CookieHandler.setDefault(new CookieManager()); 

by

CookieHandler.setDefault( new CookieManager( null, CookiePolicy.ACCEPT_ALL ) );

It work!

pramoth
  • 746
  • 7
  • 5
  • 1
    Thanks. Works brilliantly. Of course, now that I know the answer, the documentation is easy to find. ;-) – Chuck Mar 24 '13 at 15:00
  • 1
    It is a nice and more compact answer than what you can usually find. Thanks! – Panayotis Feb 23 '14 at 20:18
  • 1
    Does this add cookies to `CookieStore` automatically or do I have to write `cookieManager.getCookieStore().add(uri,hc);` every time? `hc` is a `HttpCookie Object`. – Mathews Mathai Mar 16 '18 at 03:33
  • 1
    this works only for the first time .. when i restart the app .. it give me error BasicNetwork.performRequest: Unexpected response code 401 .. please help! – Vivek Kumar Oct 30 '18 at 10:51