HttpCookie

java.net.HttpCookie Example

In this example we shall show you how to make use of HttpCookie class, HttpCookie is used to implement the HTTP state management mechanism which specifies a way to create a stateful session with HTTP requests and responses.

Generally, HTTP request/response pairs are independent of each other. However, the state management mechanism enables clients and servers to exchange state information and put these pairs in a larger context, which is called a session. The state information used to create and maintain the session is called a cookie.

A cookie is a piece of data that can be stored in a browser’s cache. If you visit a web site and then revisit it, the cookie data can be used to identify you as a return visitor. Cookies enable state information, such as an online shopping cart, to be remembered. A cookie can be short term, holding data for a single web session, that is, until you close the browser, or a cookie can be longer term, holding data for a week or a year.

Let’s see the below example which shows how to obtain all Http Cookies when we connect to facebook.com and provides complete information about those cookies like max age, domain name, value path etc.

Example:

HttpCookieTest.java:

package com.jcg;

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;

/**
 * @author ashraf
 *
 */
public class HttpCookieTest {

	/**
	 * @param args
	 * @throws IOException 
	 */
	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 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: reg_fb_gate
Domain: .facebook.com
Max age: -1
Server path: /
Is secured: false
Cookie value: https%3A%2F%2Fwww.facebook.com%2F
Cookie protocol version: 0
------------------ Cookie.2 ------------------
Cookie name: reg_fb_ref
Domain: .facebook.com
Max age: -1
Server path: /
Is secured: false
Cookie value: https%3A%2F%2Fwww.facebook.com%2F
Cookie protocol version: 0
------------------ Cookie.3 ------------------
Cookie name: datr
Domain: .facebook.com
Max age: 63071999
Server path: /
Is secured: false
Cookie value: ElIxVBBVUE8ODDu-dVnn7Fec
Cookie protocol version: 0

Explanation:
In the above example, we create and set a system-wide CookieManager using the following code:

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);

The first line calls the default CookieManager constructor to create a new CookieManager instance with a default cookie store and accept policy. The second line calls the static setDefault method of CookieHandler to set the system-wide handler.

After that, we open a connection with facebook.com to get all the available cookies. Finally, we retrieve all cookies from the cookie store using the below code then we print information about those cookies like max age, domain name, value path etc.

CookieStore cookieStore = cookieManager.getCookieStore();
List cookies = cookieStore.getCookies();

Tip

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

Download the Source Code of this example:

This was an example of how to use HttpCookie class.

Download
You can download the full source code of this example here: java.net.HttpCookie Example Code

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button