java.net.CookieHandler Class in Java
Last Updated :
10 Mar, 2021
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
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
{
CookieManager c = new CookieManager();
CookieHandler.setDefault(c);
URL url = new URL(uri);
URLConnection connection = url.openConnection();
connection.getContent();
CookieStore cookieStore = c.getCookieStore();
List<HttpCookie> cookieList
= cookieStore.getCookies();
for (HttpCookie cookie : cookieList) {
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. |
Share your thoughts in the comments
Please Login to comment...