Skip to content
Related Articles

Related Articles

java.net.CookieHandler Class in Java

View Discussion
Improve Article
Save Article
  • Last Updated : 10 Mar, 2021
View Discussion
Improve Article
Save Article

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 CookieHandler that too employed by the HTTP protocol handler is often registered by doing a CookieHandler.setDefault(CookieHandler). The currently registered CookieHandler are often retrieved by calling CookieHandler.getDefault().

Declaration:

public abstract class CookieHandler
extends Object

Constructor:

CookieHandler();

Example:

Java




// Java program to demonstrate the usage
// of CookieHandler Class
  
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 JavaCookieHandlerExample1 {
    public static void main(String args[]) throws Exception
    {
  
        String uri = "https://www.google.com";
  
        // Instantiate CookieManager;
        CookieManager c = new CookieManager();
  
        // First set the default cookie manager.
        CookieHandler.setDefault(c);
        URL url = new URL(uri);
  
        // All the following subsequent URLConnections
        // will use the same cookie manager.
        URLConnection connection = url.openConnection();
        connection.getContent();
  
        // Get cookies from underlying CookieStore
        CookieStore cookieStore = c.getCookieStore();
  
        List<HttpCookie> cookieList
            = cookieStore.getCookies();
  
        for (HttpCookie cookie : cookieList) {
  
            // Get domain set for the cookie
            System.out.println("The domain is: "
                               + cookie.getDomain());
        }
    }
}


 

Output:

The domain is: .google.com

The CookieHandler class provides the following methods in Java:

Method Description
get(URI uri, Map<String, List<String> >requestHeaders) This method gets all the applicable cookies from a cookie cache for the specified URI in the request header.
getDefault() This method gets the system-wide cookie handler.
put(URI uri, Map<String, List<String> > responseHeaders) This method sets all the applicable cookies, examples are response header fields that are named Set-Cookie2, present in the response headers into a cookie cache.
setDefault(CookieHandler cHandler) This method sets or unsets the system-wide cookie handler.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!