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 :
Syntax : public static List parse(String header)
Parameters :
header : String to be parsed as cookies
Syntax : public boolean hasExpired()
Syntax : public void setComment(String purpose)
Parameters :
purpose : purpose of cookie
Syntax : public void getComment()
Syntax : public void setCommentURL(String purpose)
Parameters :
purpose : purpose of cookie
Syntax : public String getComment()
Syntax : public void setDiscard(Boolean discard)
Parameters :
discard : true if UA should discard, otherwise false
Syntax : public Boolean getDiscard()
Syntax : public void setPortList(String portList)
Parameters :
portList : String of comma separated digits specifying the ports.
Syntax : public String getPortList()
Syntax : public void setDomain(String domain)
Parameters :
domain : String representing the domain in which this cookie is visible
Syntax : public String getDomain()
Syntax : public void setMaxAge(long age)
Parameters :
age : Max survive time in seconds
Syntax : public long getMaxAge()
Syntax : public void setPath(String uri)
Parameters :
uri - a String specifying a path
Syntax : public String getPath()
// 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());
}
}
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
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.
Syntax : public boolean getSecure()
Syntax : public String getName()
Syntax : public void setValue(String newValue)
Parameters :
newValue - a String specifying the new value
Syntax : public String getValue()
Syntax : public int getVersion()
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
Syntax : public boolean isHttpOnly()
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.
Syntax : public static boolean domainMatches(String domain,
String host)
Parameters :
domain : domain to check hostname with
host : host to check
Syntax :public String toString()
Syntax :public boolean equals(Object obj)
Syntax : public int hashCode()
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 DocumentationRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4