The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
java.net.CookieManager
provides a concrete implementation of a CookieHandler
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. A CookieManager
is initialized with a java.net.CookieStore
and a java.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:
java.net.CookieManager cm = new java.net.CookieManager(); java.net.CookieHandler.setDefault(cm);
The first line calls the default CookieManager
constructor to create the instance. The second line calls the static setDefault
method of CookieHandler
to set the system-wide handler.
The default CookieManager
constructor creates a new CookieManager
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, a CookieManager
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
is CookiePolicy.ACCEPT_ORIGINAL_SERVER
, which only accepts cookies from the original server. So, the Set-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, see java.net.HttpCookie.domainMatches
. Users requiring a different policy must implement the CookiePolicy
interface and pass it to the CookieManager
constructor or set it to an already constructed CookieManager
instance by using the setCookiePolicy(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 for CookieStore
. CookieManager
is highly customizable by enabling you to set your own CookieStore
, CookiePolicy
, or both.