gcode
gcode

Reputation: 2989

Serializing a CookieManager/CookieStore

I'm making a Java program that accesses a website, which depends on handing out cookies so I can be logged in. I've found out that using a CookieManager will allow my URLConnection to atleast gather these cookies, but then how do I have these cookies persist when the java program is closed?

I already have a class that manages serialization of a few variables, so how can I implement cookies into this serialization process? Java apparently doesn't allow me to serialize CookieManagers and CookieStores by default.

Upvotes: 3

Views: 1719

Answers (2)

cghislai
cghislai

Reputation: 1801

You can use a cookie manager that keeps all cookie headers in a serializable map. You can call the put method to make it parse cookie headers again.

public class KeepHeadersCookieManager extends CookieManager {

    private Map<URI, Map<String, List<String>>> cookieHeaders = new HashMap<>();

    public KeepHeadersCookieManager() {
    }

    public KeepHeadersCookieManager(Map<URI, Map<String, List<String>>> cookieHeaders) throws IOException {
        for (URI u : cookieHeaders.keySet()) {
            put(u, cookieHeaders.get(u));
        }
    }

    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
        super.put(uri, responseHeaders);

        Map<String, List<String>> uriCookiesHeaders = cookieHeaders.computeIfAbsent(uri, u -> new HashMap<>());
        List<String> uriSetCookieHeaders = uriCookiesHeaders.computeIfAbsent("Set-Cookie", h -> new ArrayList<>());
        List<String> uriSetCookie2Headers = uriCookiesHeaders.computeIfAbsent("Set-Cookie2", h -> new ArrayList<>());
        List<String> setCookieHeaders = responseHeaders.getOrDefault("Set-Cookie", new ArrayList<>());
        List<String> setCookie2Headers = responseHeaders.getOrDefault("Set-Cookie2", new ArrayList<>());
        uriSetCookieHeaders.addAll(setCookieHeaders);
        uriSetCookie2Headers.addAll(setCookie2Headers);
    }

    public Map<URI, Map<String, List<String>>> getCookieHeaders() {
        return cookieHeaders;
    }
}

That way, you can call getCookieHeaders() to get a serializable map of all cookies headers, and pass it back to the constructor to initialize the cookie manager from a previous state.

Upvotes: 0

Aidanc
Aidanc

Reputation: 7011

You could extend CookieManager and make it implement serializable. Then use the extended CookieManager you just created.

For example:

public class NewCookieManager extends CookieManager implements Serializable{
  //Code here...
}

Upvotes: 2

Related Questions