Top Description Inners Fields Constructors Methods
java.net

public final Class HttpCookie

extends Object
implements Cloneable
Class Inheritance
All Implemented Interfaces
java.lang.Cloneable
Imports
java.util.List, .StringTokenizer, .NoSuchElementException, .TimeZone, .Calendar, .GregorianCalendar, .Locale, .Objects, java.text.SimpleDateFormat, jdk.internal.access.JavaNetHttpCookieAccess, .SharedSecrets

An HttpCookie object represents an HTTP cookie, which carries state information between server and user agent. Cookie is widely adopted to create stateful sessions.

There are 3 HTTP cookie specifications:

Netscape draft
RFC 2109 - http://www.ietf.org/rfc/rfc2109.txt
RFC 2965 - http://www.ietf.org/rfc/rfc2965.txt

HttpCookie class can accept all these 3 forms of syntax.

Author
Edward Wang
Since
1.6
External Specification
https://www.rfc-editor.org/info/rfc2109, https://www.rfc-editor.org/info/rfc2965

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static interface

Field Summary

Modifier and TypeField and Description
pack-priv static final Map<String, HttpCookie.CookieAttributeAssignor>
private String
private String
private String
pack-priv static final TimeZone
private final String
private boolean
private static final long
private long
private final String
private String
private String
private boolean
private static final String
private static final String
private boolean
private static final String
private String
private int
private final long

Constructor Summary

AccessConstructor and Description
public
HttpCookie(String
a String specifying the name of the cookie
name
,
String
a String specifying the value of the cookie
value
)

Constructs a cookie with a specified name and value.

private
HttpCookie(String name, String value, String header)

pack-priv
HttpCookie(String name, String value, String header, long creationTime)

Package private for testing purposes.

Method Summary

Modifier and TypeMethod and Description
private static void
assignAttribute(HttpCookie cookie, String attrName, String attrValue)

public Object

Returns:

a clone of this HTTP cookie
clone
()

Overrides java.lang.Object.clone.

Create and return a copy of this object.

public static boolean

Returns:

true if they domain-matches; false if not
domainMatches
(String
the domain name to check host name with
domain
,
String
the host name in question
host
)

The utility method to check whether a host name is in a domain or not.

public boolean

Returns:

true if two HTTP cookies equal to each other; otherwise, false
equals
(Object
the reference object with which to compare.
obj
)

Overrides java.lang.Object.equals.

Test the equality of two HTTP cookies.

private static boolean
private long
public String

Returns:

a String containing the comment, or null if none
getComment
()

Returns the comment describing the purpose of this cookie, or null if the cookie has no comment.

public String

Returns:

a String containing the comment URL, or null if none
getCommentURL
()

Returns the comment URL describing the purpose of this cookie, or null if the cookie has no comment URL.

pack-priv long
public boolean

Returns:

a boolean to represent this cookie's discard attribute
getDiscard
()

Returns the discard attribute of the cookie

public String

Returns:

a String containing the domain name
getDomain
()

Returns the domain name set for this cookie.

public long

Returns:

an integer specifying the maximum age of the cookie in seconds
getMaxAge
()

Returns the maximum age of the cookie, specified in seconds.

public String

Returns:

a String specifying the cookie's name
getName
()

Returns the name of the cookie.

public String

Returns:

a String specifying a path that contains a servlet name, for example, /catalog
getPath
()

Returns the path on the server to which the browser returns this cookie.

public String

Returns:

a String contains the port list or null if none
getPortlist
()

Returns the port list attribute of the cookie

public boolean

Returns:

false if the cookie can be sent over any standard protocol; otherwise, true
getSecure
()

Returns true if sending this cookie should be restricted to a secure protocol, or false if it can be sent using any protocol.

public String

Returns:

a String containing the cookie's present value
getValue
()

Returns the value of the cookie.

public int

Returns:

0 if the cookie complies with the original Netscape specification; 1 if the cookie complies with RFC 2965/2109
getVersion
()

Returns the version of the protocol this cookie complies with.

private static int
public boolean

Returns:

true to indicate this HTTP cookie has expired; otherwise, false
hasExpired
()

Reports whether this HTTP cookie has expired or not.

public int

Returns:

this HTTP cookie's hash code
hashCode
()

Overrides java.lang.Object.hashCode.

Returns the hash code of this HTTP cookie.

private String
public boolean

Returns:

true if this cookie should be considered HTTPOnly
isHttpOnly
()

Returns true if this cookie contains the HttpOnly attribute.

private static boolean
isToken(String value)

public static List<HttpCookie>

Returns:

a List of cookie parsed from header line string
parse
(String
a String specifying the set-cookie header. The header should start with "set-cookie", or "set-cookie2" token; or it should have no leading token at all.
header
)

Constructs cookies from set-cookie or set-cookie2 header string.

private static List<HttpCookie>
parse(String header, boolean retainHeader)

private static HttpCookie
parseInternal(String header, boolean retainHeader)

public void
setComment(String
a String specifying the comment to display to the user
purpose
)

Specifies a comment that describes a cookie's purpose.

public void
setCommentURL(String
a String specifying the comment URL to display to the user
purpose
)

Specifies a comment URL that describes a cookie's purpose.

public void
setDiscard(boolean
true indicates to discard cookie unconditionally
discard
)

Specify whether user agent should discard the cookie unconditionally.

public void
setDomain(String
a String containing the domain name within which this cookie is visible; form is according to RFC 2965
pattern
)

Specifies the domain within which this cookie should be presented.

public void
setHttpOnly(boolean
if true make the cookie HTTP only, i.e. only visible as part of an HTTP request.
httpOnly
)

Indicates whether the cookie should be considered HTTP Only.

public void
setMaxAge(long
an integer specifying the maximum age of the cookie in seconds; if zero, the cookie should be discarded immediately; otherwise, the cookie's max age is unspecified.
expiry
)

Sets the maximum age of the cookie in seconds.

public void
setPath(String
a String specifying a path
uri
)

Specifies a path for the cookie to which the client should return the cookie.

public void
setPortlist(String
a String specify the port list, which is comma separated series of digits
ports
)

Specify the portlist of the cookie, which restricts the port(s) to which a cookie may be sent back in a Cookie header.

public void
setSecure(boolean
If true, the cookie can only be sent over a secure protocol like HTTPS. If false, it can be sent over any protocol.
flag
)

Indicates whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.

public void
setValue(String
a String specifying the new value
newValue
)

Assigns a new value to a cookie after the cookie is created.

public void
setVersion(int
0 if the cookie should comply with the original Netscape specification; 1 if the cookie should comply with RFC 2965/2109
v
)

Sets the version of the cookie protocol this cookie complies with.

private static List<String>
private static boolean
private static String
private String
private String
public String

Returns:

a string form of the cookie. The string has the defined format
toString
()

Overrides java.lang.Object.toString.

Constructs a cookie header string representation of this cookie, which is in the format defined by corresponding cookie specification, but without the leading "Cookie:" token.

Inherited from java.lang.Object:
finalizegetClassnotifynotifyAllwaitwaitwait

Field Detail

assignorsback to summary
pack-priv static final Map<String, HttpCookie.CookieAttributeAssignor> assignors
commentback to summary
private String comment
commentURLback to summary
private String commentURL
domainback to summary
private String domain
GMTback to summary
pack-priv static final TimeZone GMT
httpOnlyback to summary
private boolean httpOnly
MAX_AGE_UNSPECIFIEDback to summary
private static final long MAX_AGE_UNSPECIFIED
maxAgeback to summary
private long maxAge
nameback to summary
private final String name
pathback to summary
private String path
portlistback to summary
private String portlist
secureback to summary
private boolean secure
SET_COOKIE2back to summary
private static final String SET_COOKIE2
toDiscardback to summary
private boolean toDiscard
tspecialsback to summary
private static final String tspecials
valueback to summary
private String value
versionback to summary
private int version
whenCreatedback to summary
private final long whenCreated

Constructor Detail

HttpCookieback to summary
public HttpCookie(String name, String value)

Constructs a cookie with a specified name and value.

The name must conform to RFC 2965. That means it can contain only ASCII alphanumeric characters and cannot contain commas, semicolons, or white space or begin with a $ character. The cookie's name cannot be changed after creation.

The value can be anything the server chooses to send. Its value is probably of interest only to the server. The cookie's value can be changed after creation with the setValue method.

By default, cookies are created according to the RFC 2965 cookie specification. The version can be changed with the setVersion method.

Parameters
name:String

a String specifying the name of the cookie

value:String

a String specifying the value of the cookie

Exceptions
IllegalArgumentException:
if the cookie name contains illegal characters
NullPointerException:
if name is null
See Also
setValue, setVersion
HttpCookieback to summary
private HttpCookie(String name, String value, String header)
HttpCookieback to summary
pack-priv HttpCookie(String name, String value, String header, long creationTime)

Package private for testing purposes.

Method Detail

assignAttributeback to summary
private static void assignAttribute(HttpCookie cookie, String attrName, String attrValue)
cloneback to summary
public Object clone()

Overrides java.lang.Object.clone.

Create and return a copy of this object.

Returns:Object

a clone of this HTTP cookie

Annotations
@Override
domainMatchesback to summary
public static boolean domainMatches(String domain, String host)

The utility method to check whether a host name is in a domain or not.

This concept is described in the cookie specification. To understand the concept, some terminologies need to be defined first:

effective host name = hostname if host name contains dot
                  or = hostname.local if not

Host A's name domain-matches host B's if:

  • their host name strings string-compare equal; or
  • A is a HDN string and has the form NB, where N is a non-empty name string, B has the form .B', and B' is a HDN string. (So, x.y.com domain-matches .Y.com but not Y.com.)

A host isn't in a domain (RFC 2965 sec. 3.3.2) if:

  • The value for the Domain attribute contains no embedded dots, and the value is not .local.
  • The effective host name that derives from the request-host does not domain-match the Domain attribute.
  • The request-host is a HDN (not IP address) and has the form HD, where D is the value of the Domain attribute, and H is a string that contains one or more dots.

Examples:

  • A Set-Cookie2 from request-host y.x.foo.com for Domain=.foo.com would be rejected, because H is y.x and contains a dot.
  • A Set-Cookie2 from request-host x.foo.com for Domain=.foo.com would be accepted.
  • A Set-Cookie2 with Domain=.com or Domain=.com., will always be rejected, because there is no embedded dot.
  • A Set-Cookie2 from request-host example for Domain=.local will be accepted, because the effective host name for the request- host is example.local, and example.local domain-matches .local.
Parameters
domain:String

the domain name to check host name with

host:String

the host name in question

Returns:boolean

true if they domain-matches; false if not

equalsback to summary
public boolean equals(Object obj)

Overrides java.lang.Object.equals.

Test the equality of two HTTP cookies.

The result is true only if two cookies come from same domain (case-insensitive), have same name (case-insensitive), and have same path (case-sensitive).

Parameters
obj:Object

Doc from java.lang.Object.equals.

the reference object with which to compare.

Returns:boolean

true if two HTTP cookies equal to each other; otherwise, false

Annotations
@Override
equalsIgnoreCaseback to summary
private static boolean equalsIgnoreCase(String s, String t)
expiryDate2DeltaSecondsback to summary
private long expiryDate2DeltaSeconds(String dateString)
getCommentback to summary
public String getComment()

Returns the comment describing the purpose of this cookie, or null if the cookie has no comment.

Returns:String

a String containing the comment, or null if none

See Also
setComment
getCommentURLback to summary
public String getCommentURL()

Returns the comment URL describing the purpose of this cookie, or null if the cookie has no comment URL.

Returns:String

a String containing the comment URL, or null if none

See Also
setCommentURL
getCreationTimeback to summary
pack-priv long getCreationTime()
getDiscardback to summary
public boolean getDiscard()

Returns the discard attribute of the cookie

Returns:boolean

a boolean to represent this cookie's discard attribute

See Also
setDiscard
getDomainback to summary
public String getDomain()

Returns the domain name set for this cookie. The form of the domain name is set by RFC 2965.

Returns:String

a String containing the domain name

See Also
setDomain
getMaxAgeback to summary
public long getMaxAge()

Returns the maximum age of the cookie, specified in seconds. By default, -1 indicating the cookie will persist until browser shutdown.

Returns:long

an integer specifying the maximum age of the cookie in seconds

See Also
setMaxAge
getNameback to summary
public String getName()

Returns the name of the cookie. The name cannot be changed after creation.

Returns:String

a String specifying the cookie's name

getPathback to summary
public String getPath()

Returns the path on the server to which the browser returns this cookie. The cookie is visible to all subpaths on the server.

Returns:String

a String specifying a path that contains a servlet name, for example, /catalog

See Also
setPath
getPortlistback to summary
public String getPortlist()

Returns the port list attribute of the cookie

Returns:String

a String contains the port list or null if none

See Also
setPortlist
getSecureback to summary
public boolean getSecure()

Returns true if sending this cookie should be restricted to a secure protocol, or false if it can be sent using any protocol.

Returns:boolean

false if the cookie can be sent over any standard protocol; otherwise, true

See Also
setSecure
getValueback to summary
public String getValue()

Returns the value of the cookie.

Returns:String

a String containing the cookie's present value

See Also
setValue
getVersionback to summary
public int getVersion()

Returns the version of the protocol this cookie complies with. Version 1 complies with RFC 2965/2109, and version 0 complies with the original cookie specification drafted by Netscape. Cookies provided by a browser use and identify the browser's cookie version.

Returns:int

0 if the cookie complies with the original Netscape specification; 1 if the cookie complies with RFC 2965/2109

See Also
setVersion
guessCookieVersionback to summary
private static int guessCookieVersion(String header)
hasExpiredback to summary
public boolean hasExpired()

Reports whether this HTTP cookie has expired or not.

Returns:boolean

true to indicate this HTTP cookie has expired; otherwise, false

hashCodeback to summary
public int hashCode()

Overrides java.lang.Object.hashCode.

Returns the hash code of this HTTP cookie. The result is the sum of hash code value of three significant components of this cookie: name, domain, and path. That is, the hash code is the value of the expression:

getName().toLowerCase().hashCode()
+ getDomain().toLowerCase().hashCode()
+ getPath().hashCode()
Returns:int

this HTTP cookie's hash code

Annotations
@Override
headerback to summary
private String header()
isHttpOnlyback to summary
public boolean isHttpOnly()

Returns true if this cookie contains the HttpOnly attribute. This means that the cookie should not be accessible to scripting engines, like javascript.

Returns:boolean

true if this cookie should be considered HTTPOnly

See Also
setHttpOnly(boolean)
isTokenback to summary
private static boolean isToken(String value)
parseback to summary
public static List<HttpCookie> parse(String header)

Constructs cookies from set-cookie or set-cookie2 header string. RFC 2965 section 3.2.2 set-cookie2 syntax indicates that one header line may contain more than one cookie definitions, so this is a static utility method instead of another constructor.

Parameters
header:String

a String specifying the set-cookie header. The header should start with "set-cookie", or "set-cookie2" token; or it should have no leading token at all.

Returns:List<HttpCookie>

a List of cookie parsed from header line string

Exceptions
IllegalArgumentException:
if header string violates the cookie specification's syntax or the cookie name contains illegal characters.
NullPointerException:
if the header string is null
parseback to summary
private static List<HttpCookie> parse(String header, boolean retainHeader)
parseInternalback to summary
private static HttpCookie parseInternal(String header, boolean retainHeader)
setCommentback to summary
public void setComment(String purpose)

Specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user. Comments are not supported by Netscape Version 0 cookies.

Parameters
purpose:String

a String specifying the comment to display to the user

See Also
getComment
setCommentURLback to summary
public void setCommentURL(String purpose)

Specifies a comment URL that describes a cookie's purpose. The comment URL is useful if the browser presents the cookie to the user. Comment URL is RFC 2965 only.

Parameters
purpose:String

a String specifying the comment URL to display to the user

See Also
getCommentURL
setDiscardback to summary
public void setDiscard(boolean discard)

Specify whether user agent should discard the cookie unconditionally. This is RFC 2965 only attribute.

Parameters
discard:boolean

true indicates to discard cookie unconditionally

See Also
getDiscard
setDomainback to summary
public void setDomain(String pattern)

Specifies the domain within which this cookie should be presented.

The form of the domain name is specified by RFC 2965. A domain name begins with a dot (.foo.com) and means that the cookie is visible to servers in a specified Domain Name System (DNS) zone (for example, www.foo.com, but not a.b.foo.com). By default, cookies are only returned to the server that sent them.

Parameters
pattern:String

a String containing the domain name within which this cookie is visible; form is according to RFC 2965

See Also
getDomain
setHttpOnlyback to summary
public void setHttpOnly(boolean httpOnly)

Indicates whether the cookie should be considered HTTP Only. If set to true it means the cookie should not be accessible to scripting engines like javascript.

Parameters
httpOnly:boolean

if true make the cookie HTTP only, i.e. only visible as part of an HTTP request.

See Also
isHttpOnly()
setMaxAgeback to summary
public void setMaxAge(long expiry)

Sets the maximum age of the cookie in seconds.

A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age.

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

Parameters
expiry:long

an integer specifying the maximum age of the cookie in seconds; if zero, the cookie should be discarded immediately; otherwise, the cookie's max age is unspecified.

See Also
getMaxAge
setPathback to summary
public void setPath(String uri)

Specifies a path for the cookie to which the client should return the cookie.

The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories. A cookie's path must include the servlet that set the cookie, for example, /catalog, which makes the cookie visible to all directories on the server under /catalog.

Consult RFC 2965 (available on the Internet) for more information on setting path names for cookies.

Parameters
uri:String

a String specifying a path

See Also
getPath
setPortlistback to summary
public void setPortlist(String ports)

Specify the portlist of the cookie, which restricts the port(s) to which a cookie may be sent back in a Cookie header.

Parameters
ports:String

a String specify the port list, which is comma separated series of digits

See Also
getPortlist
setSecureback to summary
public void setSecure(boolean flag)

Indicates whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.

The default value is false.

Parameters
flag:boolean

If true, the cookie can only be sent over a secure protocol like HTTPS. If false, it can be sent over any protocol.

See Also
getSecure
setValueback to summary
public void setValue(String newValue)

Assigns a new value to a cookie after the cookie is created. If you use a binary value, you may want to use BASE64 encoding.

With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.

Parameters
newValue:String

a String specifying the new value

See Also
getValue
setVersionback to summary
public void setVersion(int v)

Sets the version of the cookie protocol this cookie complies with. Version 0 complies with the original Netscape cookie specification. Version 1 complies with RFC 2965/2109.

Parameters
v:int

0 if the cookie should comply with the original Netscape specification; 1 if the cookie should comply with RFC 2965/2109

Exceptions
IllegalArgumentException:
if v is neither 0 nor 1
See Also
getVersion
splitMultiCookiesback to summary
private static List<String> splitMultiCookies(String header)
startsWithIgnoreCaseback to summary
private static boolean startsWithIgnoreCase(String s, String start)
stripOffSurroundingQuoteback to summary
private static String stripOffSurroundingQuote(String str)
toNetscapeHeaderStringback to summary
private String toNetscapeHeaderString()
toRFC2965HeaderStringback to summary
private String toRFC2965HeaderString()
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Constructs a cookie header string representation of this cookie, which is in the format defined by corresponding cookie specification, but without the leading "Cookie:" token.

Returns:String

a string form of the cookie. The string has the defined format

Annotations
@Override
java.net back to summary

pack-priv Interface HttpCookie.CookieAttributeAssignor


Method Summary

Modifier and TypeMethod and Description
public void
assign(HttpCookie cookie, String attrName, String attrValue)

Method Detail

assignback to summary
public void assign(HttpCookie cookie, String attrName, String attrValue)