java.net.CookieManager
provides a concrete implementation of aCookieHandler
and for most users is sufficient for handling HTTP state management.CookieManager
separates the storage of cookies from the policy surrounding, accepting, and rejecting them. ACookieManager
is initialized with ajava.net.CookieStore
and ajava.net.CookiePolicy
.CookieStore
manages the storage of the cookies.CookiePolicy
makes policy decisions on cookie acceptance and rejection.The following code shows how to create and set a system-wide CookieManager:
The first line calls the defaultjava.net.CookieManager cm = new java.net.CookieManager(); java.net.CookieHandler.setDefault(cm);CookieManager
constructor to create the instance. The second line calls the staticsetDefault
method ofCookieHander
to set the system-wide handler.The default
CookieManager
constructor creates a newCookieManager
instance with a default cookie store and accept policy.CookieStore
is the place where any accepted HTTP cookie is stored. If not specified when created, aCookieManager
instance will use an internal in-memory implementation. This implementation is not persistent and only lives for the lifetime of the Java Virtual Machine. Users requiring a persistent store must implement their own store.The default cookie policy used by
CookieManager
isCookiePolicy.ACCEPT_ORIGINAL_SERVER
, which only accepts cookies from the original server. So, theSet-Cookie
response from the server must have a “domain” attribute set, and it must match the domain of the host in the URL. For more information, seejava.net.HttpCookie.domainMatches
. Users requiring a different policy must implement theCookiePolicy
interface and pass it to theCookieManager
constructor or set it to an already constructedCookieManager
instance by using thesetCookiePolicy(cookiePolicy)
method.When retrieving cookies from the cookie store,
CookieManager
also enforces the path-match rule from section 3.3.4 of RFC 2965. So, a cookie must also have its “path” attribute set so that the path-match rule can be applied before the cookie is retrieved from the cookie store.In summary,
CookieManager
provides the framework for handling cookies and provides a good default implementation forCookieStore
.CookieManager
is highly customizable by enabling you to set your ownCookieStore
,CookiePolicy
, or both.