Java url set cookie

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:

Constructor Summary

Method Summary

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

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

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

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.

Methods inherited from class java.lang.Object

Constructor Detail

HttpCookie

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.

Method Detail

parse

public static ListHttpCookie> 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.

hasExpired

public boolean hasExpired()

setComment

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.

getComment

setCommentURL

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.

getCommentURL

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

setDiscard

public void setDiscard(boolean discard)

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

getDiscard

public boolean getDiscard()

setPortlist

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

getPortlist

setDomain

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.

Читайте также:  HTML Frames

getDomain

setMaxAge

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.

getMaxAge

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

setPath

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.

getPath

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

setSecure

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 .

getSecure

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

getName

setValue

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.

getValue

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.

setVersion

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.

isHttpOnly

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.

setHttpOnly

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.

domainMatches

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:

  • 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.)
Читайте также:  Find the divisors python

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.
  • 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.

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.

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).

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:

clone

Источник

The following code gets the cookie value from the server. It looks at the header name Set-Cookie and uses regular expression ;\\s* to split the set cookie command.

import java.net.URL; import java.net.URLConnection; // ja va2 s . c o m public class Main < public static void main(String[] argv) throws Exception < URL url = new URL("http://java2s.com"); URLConnection conn = url.openConnection(); for (int i = 0;; i++) < String headerName = conn.getHeaderFieldKey(i); String headerValue = conn.getHeaderField(i); if (headerName == null && headerValue == null) < break; > if ("Set-Cookie".equalsIgnoreCase(headerName)) < String[] fields = headerValue.split(";\\s*"); for (int j = 1; j < fields.length; j++) < if ("secure".equalsIgnoreCase(fields[j])) < System.out.println("secure=true"); > else if (fields[j].indexOf('=') > 0) < String[] f = fields[j].split(" expires".equalsIgnoreCase(f[0])) < System.out.println("expires"+ f[1]); > else if ("domain".equalsIgnoreCase(f[0])) < System.out.println("domain"+ f[1]); > else if ("path".equalsIgnoreCase(f[0])) < System.out.println("path"+ f[1]); > > > > > > > 

The code above generates the following result.

import java.net.URL; import java.net.URLConnection; // j av a 2s . c o m public class Main < public static void main(String[] argv) throws Exception < URL url = new URL("http://hostname:80"); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", "name1=value1; name2=value2"); conn.connect(); > > 

Next chapter.

What you will learn in the next chapter:

Источник

The HTTP state management mechanism specifies a way to create a stateful session with HTTP requests and responses. The specification for it can be found in RFC 2965: HTTP State Management Mechanism at http://www.ietf.org/rfc/rfc2965.txt?number=2965.

Prior to JDK 5.0 support

Prior to JDK 5.0, it was possible to add Cookie management to applications. But the supporting API was somewhat rudimentary. There was no single point of hook up with cookie management. Each application had to handle cookies for each HTTP request/response separately by using the following two methods from java.net.URLConnection class:

Читайте также:  Javascript узнать координаты элемента

The first method should be called before sending out a HTTP request in order to set the appropriate cookies for the current URL in the HTTP headers. The second method should be used to retrieve the cookies from the response headers sent by the HTTP server.

Although doable, adding Cookie support in this way results in fragmented code, which is error prone and incurs high maintenance.

What’s new in JDK 5.0?

JDK 5.0 introduced a new callback mechanism via an abstract class to hook up a HTTP state management policy implementation into the HTTP protocol handler. Applications and web containers can introduce Cookie management by providing a concrete subclass of the new API.

The new abstract class is called java.net.CookieHandler. It provides a mechanism to register and retrieve the current CookieHandler for the JVM, as well as methods to retrieve and record relevant cookies for a specific URI.

There are two static methods in CookieHandler getDefault() and setDefault() for retrieving and registering the default CookieHandler in the VM. As well as two instance methods get() and put() for returning a list of cookies based on a URL and stores a list of cookies from the response headers, respectively.

Cookies are represented as Map>, a Map from the header field name for cookies to a list of cookies represented by Strings. There are two state management headers defined so far, «Set-Cookie2» and «Cookie». The former is used for returning cookies in response headers; while the latter is for setting cookies in HTTP request headers.

Here is an example from RFC2965:

POST /acme/login HTTP/1.1
[form data]

HTTP/1.1 200 OK
Set-Cookie2: Customer=»WILE_E_COYOTE»; Version=»1″; Path=»/acme»

POST /acme/pickitem HTTP/1.1
Cookie: $Version=»1″; Customer=»WILE_E_COYOTE»; $Path=»/acme»
[form data]

A simple Example

Here’s a simple example of a CookieHandler implementation. Basically there are two methods to implement, given a request URI and request headers (except the cookie headers), retrieve all the relevant cookies from your cookie cache; and record the applicable cookies to your cookie cache given the request URI and the response headers.

class MyCookieHandler extends CookieHandler < public Map> get(URI uri, Map> requestHeaders) throws IOException < // the cookies will be included in request Map> map = new HashMap>(); List l = retrieveCookies(uri, rqstHdrs); map.put("Cookie",l); return Collections.unmodifiableMap(map); > public void put(URI uri, Map responseHeaders) throws IOException < // check response has cookies[1] List l = (List)responseHeaders.get("Set-Cookie2"); if (l != null) < // save the cookies in a cookie cache storeCookies(uri, l); >> >

The methods retrieveCookies() and storeCookies() are «magic» functions for interacting with a backend cookie management facility, which is omitted in this example.

Once it is registered with the VM, it will take effect when you issue HTTP transactions.

public static void main(String args[]) throws Exception

There is no default implementation of a cookie manager in Java SE. However, this may change in the future. Java Plugin and Java WebStart provides a default CookieHandler in their environment.

Источник

Оцените статью