java.net.CookieManagerprovides a concrete implementation of aCookieHandlerand for most users is sufficient for handling HTTP state management.CookieManagerseparates the storage of cookies from the policy surrounding, accepting, and rejecting them. ACookieManageris initialized with ajava.net.CookieStoreand ajava.net.CookiePolicy.CookieStoremanages the storage of the cookies.CookiePolicymakes 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);CookieManagerconstructor to create the instance. The second line calls the staticsetDefaultmethod ofCookieHanderto set the system-wide handler.The default
CookieManagerconstructor creates a newCookieManagerinstance with a default cookie store and accept policy.CookieStoreis the place where any accepted HTTP cookie is stored. If not specified when created, aCookieManagerinstance 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
CookieManagerisCookiePolicy.ACCEPT_ORIGINAL_SERVER, which only accepts cookies from the original server. So, theSet-Cookieresponse 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 theCookiePolicyinterface and pass it to theCookieManagerconstructor or set it to an already constructedCookieManagerinstance by using thesetCookiePolicy(cookiePolicy)method.When retrieving cookies from the cookie store,
CookieManageralso 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,
CookieManagerprovides the framework for handling cookies and provides a good default implementation forCookieStore.CookieManageris highly customizable by enabling you to set your ownCookieStore,CookiePolicy, or both.