Java.net.HttpCookie in Java
Last Updated :
26 Jul, 2024
Prerequisite – Cookies
Many websites use small strings of text known as cookies to store persistent client-side state between connections. Cookies are passed from server to client and back again in the HTTP headers of requests and responses. Cookies can be used by a server to indicate session IDs, shopping cart contents, login credentials, user preferences, and more. 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:
HttpCookie class can accept all these 3 forms of syntax.
Constructor :
Creates a cookie with the specified name and value. The name must contain only ASCII alphanumeric characters and conform to RFC 2965. It throws an IllegalArgument exception if the name is not correct or NullPointerException if name is null. The value can be anything cookie wanna store.
Syntax : public HttpCookie(String name,
String value)
Parameters :
name : name of cookie
value : value of cookie
Throws :
IllegalArgumentException : if name does not conform to RFC2965
NullPointerException : if name is null
Methods :
- parse() : returns a list of cookies parsed from header string. header must begin with set-cookie or set-cookie2 token or must not contain any token at all.
Syntax : public static List parse(String header)
Parameters :
header : String to be parsed as cookies
- hasExpired() : returns boolean value indicating whether the cookie has expired or not.
Syntax : public boolean hasExpired()
- setComment() : Used to set a short description describing the purpose of the cookie. It is used when to present the cookie to the user.
Syntax : public void setComment(String purpose)
Parameters :
purpose : purpose of cookie
- getComment() : Returns the description of the cookie, or null if cookie has no comments.
Syntax : public void getComment()
- setCommentURL() : Used to set a short comment url describing the purpose of the cookie. It is used when browser presents the cookie to the user.
Syntax : public void setCommentURL(String purpose)
Parameters :
purpose : purpose of cookie
- getCommentURL() : Returns the URL comment of the cookie, or null if cookie has no URL comments.
Syntax : public String getComment()
- setDiscard() : Used to set if the user agent should discard this cookie or not.
Syntax : public void setDiscard(Boolean discard)
Parameters :
discard : true if UA should discard, otherwise false
- getDiscard() : Returns the state of discard variable set by setDiscard() method. More specifically returns true if UA is to discard this cookie, otherwise false.
Syntax : public Boolean getDiscard()
- setPortList() : Used to specify the ports which this cookie can use.
Syntax : public void setPortList(String portList)
Parameters :
portList : String of comma separated digits specifying the ports.
- getPortList() : Returns the list of ports which this cookie can use.
Syntax : public String getPortList()
- setDomain() : Specify the domain in which this cookie should be visible. For instance, cookies sent from a servlet at bali.vacations.com would not normally get returned by the browser to pages at queensland.vacations.com. If the site wanted this to happen, the servlets could specify cookie.setDomain(“.vacations.com”). To prevent servers from setting cookies that apply to hosts outside their domain, the specified domain must meet the following requirements: it must start with a dot (e.g., .coreservlets.com).
Syntax : public void setDomain(String domain)
Parameters :
domain : String representing the domain in which this cookie is visible
- getDomain() : Returns the domain in which this cookie is visible.
Syntax : public String getDomain()
- setMaxAge() : used to set the max age of cookie in seconds. It specifies the maximum time after creation of cookie for which it is alive. Negative values specifies that cookie will expire as soon as browser exits.
Syntax : public void setMaxAge(long age)
Parameters :
age : Max survive time in seconds
- getMaxAge() : Returns the max age of cookie.
Syntax : public long getMaxAge()
- setPath() : Used to specify the path to the client at which it should return the cookie. This cookie is visible to all the pages and subdirectories of the path specified. For example, if the server sent the cookie from http://ecommerce.site.com/toys/specials.html, the browser would send the cookie back when connecting to http://ecommerce.site.com/to/beginners.html, butnot to http://ecommerce.site.com/c/classic.html.
Syntax : public void setPath(String uri)
Parameters :
uri - a String specifying a path
- getPath() : Returns the path set for this cookie.
Syntax : public String getPath()
- Java Implementation :
-
Java
// Java Program to illustrate various
// methods of java.net.HttpCookie class
public class httpcookie1
{
public static void main(String[] args)
{
// Constructor to create a new cookie.
HttpCookie cookie = new HttpCookie("First", "1");
// setComment() method
cookie.setComment("Just for explanation");
// getComment() method
System.out.println("Comment : " + cookie.getComment());
// setCommentURL() method
cookie.setCommentURL("192.168.1.1");
// getCommentURL() method
System.out.println("CommentURL : " + cookie.getCommentURL());
// setDiscard() method
cookie.setDiscard(true);
// getDiscard() method
System.out.println("Discard : " + cookie.getDiscard());
// setPortlist() method
cookie.setPortlist("1001,8520");
// getPortList() method
System.out.println("Ports: " + cookie.getPortlist());
// setDomain() method
cookie.setDomain(".localhost.com");
// getDomain() method
System.out.println("Domain : " + cookie.getDomain());
// setMaxAge() method
cookie.setMaxAge(3600);
// getMaxAge() method
System.out.println("Max Age : " + cookie.getMaxAge());
// setPath() method
cookie.setPath("192.168.1.1/admin/index.html");
// getPath() method
System.out.println("Path: " + cookie.getPath());
}
}
- Output
Comment : Just for explanation
CommentURL : 192.168.1.1
Discard : true
Ports: 1001,8520
Domain : .localhost.com
Max Age : 3600
Path: 192.168.1.1/admin/index.html
- setSecure() : Indicated if secure protocol to be used while sending this cookie. Default value is false.
Syntax : public void setSecure(boolean secure)
Parameters:
secure - If true, the cookie can only be sent over a secure protocol like https.
If false, it can be sent over any protocol.
- getSecure() : Returns true if this cookie must be sent by a secure protocol, otherwise false.
Syntax : public boolean getSecure()
- getName() : Returns the name of the cookie.
Syntax : public String getName()
- setValue() : Assigns new value to cookie after initialisation.
Syntax : public void setValue(String newValue)
Parameters :
newValue - a String specifying the new value
- getValue : Returns the value of the cookie.
Syntax : public String getValue()
- getVersion() : Returns 0 if the cookie complies with the original Netscape specification; 1 if the cookie complies with RFC 2965/2109
Syntax : public int getVersion()
- setVersion() : Used to set the version of the cookie protocol this cookie uses.
Syntax :public void setVersion(int v)
throws IllegalArgumentException
Parameters :
v - 0 for original Netscape specification; 1 for RFC 2965/2109
Throws :
IllegalArgumentException - if v is neither 0 nor 1
- isHttpOnly() :Returns true if cookie can only be used by http ie it cannot be used by scripting languages like JS, vb etc.
Syntax : public boolean isHttpOnly()
- setHttpOnly() : Used to set if this cookie is http only or not.
Syntax : public void setHttpOnly(boolean httpOnly)
Parameters :
httpOnly - if true make the cookie HTTP only, i.e. only visible as part
of an HTTP request.
- domainMatches() : Utility function to check if hostname is in domain or not.
Syntax : public static boolean domainMatches(String domain,
String host)
Parameters :
domain : domain to check hostname with
host : host to check
- toString() : Constructs a string representation of this cookie.
Syntax :public String toString()
- equals() : returns true if two http cookies are equal to each other, false otherwise.
Syntax :public boolean equals(Object obj)
- hashCode() :Return 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. Overrides hashCode in class Object.
Syntax : public int hashCode()
- clone() : Create and return a copy of this object. Overrides clone method of object class.
Syntax : public Object clone()
Java Implementation :
Java
// Java Program to illustrate various
// methods of java.net.HttpCookie class
import java.net.HttpCookie;
public class httpcookie1
{
public static void main(String[] args)
{
// Constructor to create a new cookie.
HttpCookie cookie = new HttpCookie("First", "1");
// setSecure() method
cookie.setSecure(true);
// getSecure() method
System.out.println("Secure : " + cookie.getSecure());
// getName() method
System.out.println("Name : " + cookie.getName());
// setValue() method : can be used to modify value of cookie.
cookie.setValue("2");
// getvalue() method
System.out.println("Value : " + cookie.getValue());
// setVersion() method
cookie.setVersion(1);
// getVersion() method
System.out.println("Version : " + cookie.getVersion());
// setHttPonly() method
cookie.setHttpOnly(true);
// isHttpOnly() method
System.out.println("is HTTP only : " + cookie.isHttpOnly());
// toString() method
System.out.println("toString : " + cookie.toString());
// hashcode() method
System.out.println("Hashcode : " + cookie.hashCode());
}
}
Output :
Secure : true
Name : First
Value : 2
Version : 1
is HTTP only : true
toString : First="2"
Hashcode : 97440432
Another Example to show how cookies are actually used by Web servers in which we print the details of cookies stored by www.facebook.com
Java
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
public class httpcookie1
{
public static void main(String[] args) throws IOException
{
String urlString = "https://www.facebook.com";
// Create a default system-wide CookieManager
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
// Open a connection for the given URL
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
urlConnection.getContent();
// Get CookieStore which is the default internal in-memory
CookieStore cookieStore = cookieManager.getCookieStore();
// Retrieve all stored HttpCookies from CookieStore
List<HttpCookie> cookies = cookieStore.getCookies();
int cookieIdx = 0;
// Iterate HttpCookie object
for (HttpCookie ck : cookies) {
System.out.println("------ Cookie." + ++cookieIdx + " -------");
// Get the cookie name
System.out.println("Cookie name: " + ck.getName());
// Get the domain set for the cookie
System.out.println("Domain: " + ck.getDomain());
// Get the max age of the cookie
System.out.println("Max age: " + ck.getMaxAge());
// Get the path of the server
System.out.println("Server path: " + ck.getPath());
// Get boolean if the cookie is being restricted to a secure
// protocol
System.out.println("Is secured: " + ck.getSecure());
// Gets the value of the cookie
System.out.println("Cookie value: " + ck.getValue());
// Gets the version of the protocol with which the given cookie is
// related.
System.out.println("Cookie protocol version: " + ck.getVersion());
}
}
}
Output :
------------------ Cookie.1 ------------------
Cookie name: fr
Domain: .facebook.com
Max age: 7775999
Server path: /
Is secured: true
Cookie value: 0Xj7tBSsWlmtXPo92..BZFC8G.qC.AAA.0.0.BZFC8G.AWUwiIgM
Cookie protocol version: 0
Reference:
Official Java Documentation
Similar Reads
Java.net.Authenticator class in Java
Authenticator class is used in those cases where an authentication is required to visit some URL. Once it is known that authentication is required, it prompts the user for the same or uses some hard-coded username and password. To use this class, following steps are followed- Create a class that ext
3 min read
Java.net.URLEncoder class in Java
This class is a utility class for HTML form encoding. Encoding makes the form of URL more reliable and secure. When the user request is triggered by a get method, the form parameters and their values are appended at the end of URL after a '?' sign. The problem arises when special characters are used
3 min read
Java.net.URLDecoder class in Java
This is a utility class for HTML form decoding. It just performs the reverse of what URLEncoder class do, i.e. given an encoded string, it decodes it using the scheme specified. Generally when accessing the contents of request using getParameter() method in servlet programming, the values are automa
2 min read
Check if URL is valid or not in Java
Given a URL as string, we need to find if the given URL is valid or not. Input : str = "https://www.geeksforgeeks.org/" Output : Yes Input : str = "https:// www.geeksforgeeks.org/" Output : No Note that there is a space after https:// Using java.net.url We can use java.net.url class to validate a UR
1 min read
The HttpSession Interface in Servlet
What is a session? In web terminology, a session is simply the limited interval of time in which two systems communicate with each other. The two systems can share a client-server or a peer-to-peer relationship. However, in Http protocol, the state of the communication is not maintained. Hence, the
4 min read
Provider entrySet() method in Java with Examples
The entrySet() method of java.security.Provider class is used to return an unmodifiable Set view of the property entries contained in this Provider. Syntax: public Set<Map.Entry> entrySet() Return Value: This method returns a set view of the mappings contained in this map Below are the example
3 min read
hmac - Keyed-Hashing for Message Authentication
HMAC is a mechanism for message authentication using cryptographic hash functions. HMAC can be used with any iterative cryptographic hash function, e.g., MD5, SHA-1, in combination with a secret shared key. This module implements the HMAC algorithm. The basic idea is to generate a cryptographic hash
3 min read
Java Swing | JPasswordField
PasswordField is a part of javax.swing package . The class JPasswordField is a component that allows editing of a single line of text where the view indicates that something was typed by does not show the actual characters. JPasswordField inherits the JTextField class in javax.swing package.Construc
5 min read
java.net.CookieHandler Class in Java
The object of the CookieHandler Class in Java provides a callback mechanism for hooking up an HTTP state management policy implementation into the HTTP protocol handler. The mechanism of how to make HTTP requests and responses is specified by the HTTP state management mechanism. A system-wide Cookie
2 min read
Servlet - Cookies
Cookies are the textual information that is stored in key-value pair format to the client's browser during multiple requests. It is one of the state management techniques in session tracking. Basically, the server treats every client request as a new one so to avoid this situation cookies are used.
4 min read