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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
------------------ Cookie.1 ------------------
Cookie name: reg_fb_gate
Domain: .facebook.com
Max age: -1
Server path: /
Is secured: false
Cookie value: https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%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%2Ffanyv88.com%3A443%2Fhttps%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:

1
2
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.

1
2
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
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button