📜  Java的.net.CookieHandler类在Java中

📅  最后修改于: 2022-05-13 01:55:08.400000             🧑  作者: Mango

Java的.net.CookieHandler类在Java中

JavaCookieHandler 类的对象提供了一种回调机制,用于将 HTTP 状态管理策略实现挂接到 HTTP 协议处理程序中。 HTTP 请求和响应的机制由 HTTP 状态管理机制规定。

HTTP 协议处理程序也使用的系统范围的 CookieHandler 通常通过执行 CookieHandler.setDefault(CookieHandler) 来注册。当前注册的 CookieHandler 通常通过调用 CookieHandler.getDefault() 来检索。

宣言:

public abstract class CookieHandler
extends Object

构造函数:

CookieHandler();

例子:



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 cookieList
            = cookieStore.getCookies();
  
        for (HttpCookie cookie : cookieList) {
  
            // Get domain set for the cookie
            System.out.println("The domain is: "
                               + cookie.getDomain());
        }
    }
}


输出:

The domain is: .google.com

CookieHandler 类在Java提供了以下方法:

MethodDescription
get(URI uri, Map >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 > 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.