JMU
Cookie Handling in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Encapsulating Cookies
Managing Cookies
An Example

Display the Cookies Set by an HTTP Response

javaexamples/internet/DisplayCookies.java
        import java.net.*;
import java.io.*;
import java.util.*;

/**
 * An application that reports on the cookies that are written in response
 * to an HTTP GET request.
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class DisplayCookies
{
    /**
     * The entry point of the application.
     * 
     * @param args Command-line arguments (args[0] is the URL)
     */
    public static void main(String[] args)
    {
        CookieManager   manager;
        CookieStore     store;
        String  arg;
        URL    url;

        // Process the command line argument
        if ((args == null) || (args.length == 0)) arg = "https://www.google.com/";
        else                                      arg = args[0];

        try
        {
            // Construct the URL
            url = new URL(arg);

            // Set the (universal) CookieHandler
            manager = new CookieManager();
            CookieHandler.setDefault(manager);
            
            // Get the CookieStore (which does not provide 
            // persistence by default)
            store = manager.getCookieStore();
            
            try
            {
                // Send the HTTP GET request. The response will
                // cause a call-back to the CookieHandler.
                InputStream in = url.openStream();
                in.close();
                
                // Print the cookies
                List<HttpCookie> cookies = store.getCookies();
                System.out.println("Cookies from " + arg);
                for (HttpCookie c: cookies)
                {
                    System.out.println(c);
                }
            }
            catch (IOException ioe)
            {
                System.out.println("Unable to make a connection.");
            }
        }
        catch (MalformedURLException mue)
        {
            System.out.println("Invalid URL: " + arg);
        }
    }
}
        
Providing Persistence