# 自定义 CookieManager

> 原文： [https://docs.oracle.com/javase/tutorial/networking/cookies/custom.html](https://docs.oracle.com/javase/tutorial/networking/cookies/custom.html)

`CookieManager`类的两个方面可以定制，`CookiePolicy`和`CookieStore`。

## 的 CookiePolicy

为方便起见，`CookiePolicy`定义了以下用于接受 cookie 的预定义策略：

*   `CookiePolicy.ACCEPT_ORIGINAL_SERVER`仅接受来自原始服务器的 cookie。
*   `CookiePolicy.ACCEPT_ALL`接受所有 cookie。
*   `CookiePolicy.ACCEPT_NONE`不接受任何 cookie。
*   You can also define your own cookie policy by implementing the `shouldAccept` method of `CookiePolicy`. You can then use this `CookiePolicy` by passing it to the multi-argument `CookieManager` constructor or by calling the `setCookiePolicy(cookiePolicy)` method to change an already existing cookie manager.

    以下是在应用`CookiePolicy.ACCEPT_ORIGINAL_SERVER`策略之前拒绝来自黑名单中的域的 cookie 的 cookie 策略的示例：

    ```
    import java.net.*;

    public class BlacklistCookiePolicy implements CookiePolicy {
        String[] blacklist;

        public BlacklistCookiePolicy(String[] list) {
            blacklist = list;
        }

        public boolean shouldAccept(URI uri, HttpCookie cookie)  {
            String host;
            try {
                host =  InetAddress.getByName(uri.getHost()).getCanonicalHostName();
            } catch (UnknownHostException e) {
                host = uri.getHost();
            }

            for (int i = 0; i&lt;blacklist.length; i++) {
    	    if (HttpCookie.domainMatches(blacklist[i], host)) {
                    return false;
                }
            }

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

    ```

    When you create a `BlacklistCookiePolicy` instance, you pass it an array of strings representing the domains that you do not want to accept cookies from. Then, you set this `BlacklistCookiePolicy` instance as the cookie policy for your `CookieManager`. For example:

    ```
    String[] list = new String[]{ ".example.com" };
    CookieManager cm = new CookieManager(null, new BlacklistCookiePolicy(list));
    CookieHandler.setDefault(cm);

    ```

    The sample code will not accept cookies from hosts such as the following:

    ```
    host.example.com
    domain.example.com

    ```

    However, this sample code will accept cookies from hosts such as the following:

    ```
    example.com
    example.org
    myhost.example.org

    ```

    ## 的 CookieStore

    A `CookieStore` is an interface that represents a storage area for cookies. `CookieManager` adds the cookies to the `CookieStore` for every HTTP response and retrieves cookies from the `CookieStore` for every HTTP request.

    您可以实现此接口以提供您自己的`CookieStore`并在创建期间将其传递给`CookieManager`。创建`CookieManager`实例后，无法设置`CookieStore`。但是，您可以通过调用`CookieManager.getCookieStore()`来获取对 cookie 存储的引用。这样做非常有用，因为它可以利用 Java SE 提供的默认内存`CookieStore`实现并补充其功能。

    例如，您可能希望创建一个可以保存 cookie 的持久性 cookie 存储，以便即使重新启动 Java 虚拟机也可以使用它们。您的实现将类似于以下内容：

    1.  之前保存的所有 Cookie 都会被读入。
    2.  在运行时，cookie 将从内存中存储和检索。
    3.  在退出之前，Cookie 会写入持久存储。

    以下是此 cookie 商店的不完整示例。此示例显示如何利用 Java SE 默认的内存中 cookie 存储以及如何扩展其功能。

    ```
    import java.net.*;
    import java.util.*;

    public class PersistentCookieStore implements CookieStore, Runnable {
        CookieStore store;

        public PersistentCookieStore() {
            // get the default in memory cookie store
            store = new CookieManager().getCookieStore();

            // todo: read in cookies from persistant storage
            // and add them store

            // add a shutdown hook to write out the in memory cookies
            Runtime.getRuntime().addShutdownHook(new Thread(this)); 
        }

        public void run() {
            // todo: write cookies in store to persistent storage
        }

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

        public List&lt;HttpCookie&gt; get(URI uri) {
            return store.get(uri);
        }

        public List&lt;HttpCookie&gt; getCookies() {
            return store.getCookies();
        }

        public List&lt;URI&gt; getURIs() {
            return store.getURIs();
        }

        public boolean remove(URI uri, HttpCookie cookie) {
            return store.remove(uri, cookie);
        }

        public boolean removeAll()  {
            return store.removeAll();
        }
    }

    ```