Java Reference
In-Depth Information
CookieManager
Java 5 includes an abstract java.net.CookieHandler class that defines an API for stor‐
ing and retrieving cookies. However, it does not include an implementation of that
abstract class, so it requires a lot of grunt work. Java 6 fleshes this out by adding a concrete
java.net.CookieManager subclass of CookieHandler that you can use. However, it is
not turned on by default. Before Java will store and return cookies, you need to enable
it:
CookieManager manager = new CookieManager ();
CookieHandler . setDefault ( manager );
If all you want is to receive cookies from sites and send them back to those sites, you're
done. That's all there is to it. After installing a CookieManager with those two lines of
code, Java will store any cookies sent by HTTP servers you connect to with the URL class,
and will send the stored cookies back to those same servers in subsequent requests.
However, you may wish to be a bit more careful about whose cookies you accept. You
can do this by specifying a CookiePolicy . Three policies are predefined:
CookiePolicy.ACCEPT_ALL All cookies allowed
CookiePolicy.ACCEPT_NONE No cookies allowed
CookiePolicy.ACCEPT_ORIGINAL_SERVER Only first party cookies allowed
For example, this code fragment tells Java to block third-party cookies but accept first-
party cookies:
CookieManager manager = new CookieManager ();
manager . setCookiePolicy ( CookiePolicy . ACCEPT_ORIGINAL_SERVER );
CookieHandler . setDefault ( manager );
That is, it will only accept cookies for the server that you're talking to, not for any server
on the Internet.
If you want more fine-grained control, for instance to allow cookies from some known
domains but not others, you can implement the CookiePolicy interface yourself and
override the shouldAccept() method:
public boolean shouldAccept ( URI uri , HttpCookie cookie )
Example 6-1 shows a simple CookiePolicy that blocks cookies from .gov domains, but
allows others.
Example 6-1. A cookie policy that blocks all .gov cookies but allows others
import java.net.* ;
public class NoGovernmentCookies implements CookiePolicy {
Search WWH ::




Custom Search