Cookie Handling in Java
An Introduction |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
Cookie
headerSet-Cookie
headerCookieHandler
Interface:
get()
gets all applicable cookies from the cache
put()
sets all applicable cookiesset()
is a static method that sets the universal
cookie handler for all subsequent HTTP connectionsCookieManager
Class:
CookieStore
to save/retrieve the cookies
CookieStore
Interface:
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); } } }
CookieStore
(and probably Runnable
for reasons discussed below)
Runtime.getRuntime().addShutdownHook()
and pass it a Thread
(with an associated
Runnable
)