Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

A Guide To HTTP Cookies In Java

$
0
0

The Master Class of "Learn Spring Security" is live:

>> CHECK OUT THE COURSE

1. Overview

In this article, we are going to explore low-level operations with Java network programming. We’ll be taking a deeper look at Cookies.

The Java platform ships with built-in networking support, bundled up in the java.net package:

import java.net.*;

2. HTTP Cookies

Whenever a client sends an HTTP request to a server and receives a response for it, the server forgets about this client. The next time the client requests again, it will be seen as a totally new client.

However, cookies, as we know, make it possible to establish a session between the client and server such that the server can remember the client across multiple request response pairs.

From this section henceforth, we will learn how to use cookies to enhance our client-server communications in Java network programming.

The main class in the java.net package for handling cookies is CookieHandler. There are other helper classes and interfaces such as CookieManager, CookiePolicy, CookieStore, and HttpCookie.

3. The CookieHandler Class

Consider this scenario; we are communicating with the server at http://baeldung.com, or any other URL that uses HTTP protocol, the URL object will be using an engine called the HTTP protocol handler.

This HTTP protocol handler checks if there is a default CookieHandler instance in the system. If there is, it invokes it to take charge of state management.

So the CookieHandler class has a purpose of providing a callback mechanism for the benefit of the HTTP protocol handler.

CookieHandler is an abstract class. It has a static getDefault() method that can be called to retrieve the current
CookieHandler installation or we can call setDefault(CookieHandler) to set our own. Note that calling setDefault installs a CookieHandler object on a system-wide basis.

It also has put(uri, responseHeaders) for saving any cookies to the cookie store. These cookies are retrieved from the response headers of the HTTP response from the given URI. It’s called every time a response is received.

A related API method – get(uri,requestHeaders) retrieves the cookies saved under the given URI and adds them to the requetHeaders. It’s called just before a request is made.

These methods must all be implemented in a concrete class of CookieHandler. At this point, the CookieManager class is worth our attention. This class offers a complete implementation of CookieHandler class for most common use cases.

In the next two sections, we are going to explore the CookieManager class; first in its default mode and later in custom mode.

4. The Default CookieManager

To have a complete cookie management framework, we need to have implementations of CookiePolicy and CookieStore.

CookiePolicy establishes the rules for accepting and rejecting cookies. We can of course change these rules to suit our needs.

Next – CookieStore does exactly what it’s name suggests, it has methods for saving and retrieving cookies. Naturally we can tweak the storage mechanism here as well if we need to.

Let’s first look at the defaults. To create the default CookieHandler and set it as the system-wide default:

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

We should note that the default CookieStore will have volatile memory i.e. it only lives for the lifetime of the JVM. To have a more persistent storage for cookies, we must customize it.

When it comes to CookiePolicy, the default implementation is CookiePolicy.ACCEPT_ORIGINAL_SERVER. This means that if the response is received through a proxy server, then the cookie will be rejected.

5. A Custom CookieManager

Let’s now customize the default CookieManager by providing our own instance of CookiePolicy or CookieStore (or both).

5.1. CookiePolicy

CookiePolicy provides some pre-defined implementations for convenience:

  • CookiePolicy.ACCEPT_ORIGINAL_SERVER – only cookies from the original server can be saved (the default implementation)
  • CookiePolicy.ACCEPT_ALL – all cookies can be saved regardless of their origin
  • CookiePolicy.ACCEPT_NONE – no cookies can be saved

To simply change the current CookiePolicy without implementing our own, we call the setCookiePolicy on the CookieManager instance:

CookieManager cm=new CookieManager();
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

But we can do a lot more customization than this. Knowing the behavior of CookiePolicy.ACCEPT_ORIGINAL_SERVER, let’s assume we trust a particular proxy server and would like to accept cookies from it on top of the original server.

We’ll have to implement the CookiePolicy interface and implement the shouldAccept method; it’s here where we’ll change the acceptance rule by adding the chosen proxy server’s domain name.

Let’s call the new policy – ProxyAcceptCookiePolicy. It will basically reject any other proxy server from its shouldAccept implementation apart from the given proxy address, then call the shouldAccept method of the CookiePolicy.ACCEPT_ORIGINAL_SERVER to complete the implementation:

public class ProxyAcceptCookiePolicy implements CookiePolicy {
    private String acceptedProxy;

    public boolean shouldAccept(URI uri, HttpCookie cookie) {
        String host = InetAddress.getByName(uri.getHost())
          .getCanonicalHostName();
        if (!HttpCookie.domainMatches(acceptedProxy, host)) {
            return false;
        }

        return CookiePolicy.ACCEPT_ORIGINAL_SERVER
          .shouldAccept(uri, cookie);
    }

    // standard constructors
}

When we create an instance of ProxyAcceptCookiePolicy, we pass in a String of the domain address we would like to accept cookies from in addition to the original server.

We then set this instance as the cookie policy of the CookieManager instance before setting it as the default CookieHandler:

CookieManager cm = new CookieManager();
cm.setCookiePolicy(new ProxyAcceptCookiePolicy("baeldung.com"));
CookieHandler.setDefault(cm);

This way the cookie handler will accept all cookies from the original server and also those from http://www.baeldung.com.

5.2. CookieStore

CookieManager adds the cookies to the CookieStore for every HTTP response and retrieves cookies from the CookieStore for every HTTP request.

The default CookieStore implementation does not have persistence, it rather loses all it’s data when the JVM is restarted. More like RAM in a computer.

So if we would like our CookieStore implementation to behave like the hard disk and retain the cookies across JVM restarts, we must customize it’s storage and retrieval mechanism.

One thing to note is that we cannot pass a CookieStore instance to CookieManager after creation. Our only option is to pass it during the creation of CookieManager or obtain a reference to the default instance by calling new CookieManager().getCookieStore() and complementing its behavior.

Here is the implementation of PersistentCookieStore:

public class PersistentCookieStore implements CookieStore, Runnable {
    private CookieStore store;

    public PersistentCookieStore() {
        store = new CookieManager().getCookieStore();
        // deserialize cookies into store
        Runtime.getRuntime().addShutdownHook(new Thread(this));
    }

    @Override
    public void run() {
        // serialize cookies to persistent storage
    }

    @Override
    public void add(URI uri, HttpCookie cookie) {
        store.add(uri, cookie);

    }
    
    // delegate all implementations to store object like above
}

Notice that we retrieved a reference to the default implementation in the constructor.

We implement runnable so that we can add a shutdown hook that runs when the JVM is shutting down. Inside the run method, we persist all our cookies into memory.

We can serialize the data into a file or any suitable storage. Notice also that inside the constructor, we first read all cookies from persistent memory into the CookieStore. These two simple features make the default CookieStore essentially persistent (in a simplistic way).

6. Conclusion

In this tutorial, we covered HTTP cookies and showed how to access and manipulate them programmatically.

The full source code for the article and all code snippets can be found in the GitHub project.

I just released the Master Class of "Learn Spring Security" Course:

>> CHECK OUT THE COURSE


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>