6

I don't know how CookieHandler works system wide, I did view the source of CookieHandler but found no more information except the get/set methods. Where do TCP/HTTP connections use instance of CookieHandler, which I set by

CookieHandler.setDefault(...)

Which source file I should refer to? URLConnection & HttpURLConnection don't seem have things to do with it.

Help, thanks in advance.


Edit: Is it possible to apply CookieHandler to only one instance in which setDefault is invoked.
user435657
  • 625
  • 2
  • 10
  • 28
  • I've been wondering the same thing. This [page](http://docs.oracle.com/javase/tutorial/networking/cookies/cookiehandler.html) might hopefully have some info, namely "That is, URLs that use HTTP as the protocol, `new URL("http://example.com")` for example, will use the HTTP protocol handler. This protocol handler calls back to the CookieHander object, if set, to handle the state management." – Tony Chan Aug 03 '12 at 01:22

2 Answers2

0

The javadoc for java.net.CookieManager gives a pretty good overview of how CookieHandler fits in.

Knut Forkalsrud
  • 1,134
  • 1
  • 7
  • 19
0

I got it working by using this

private static class DelegatingCookieManager extends CookieManager {
    @Override public void setCookiePolicy(CookiePolicy cookiePolicy) {
        delegate.get().setCookiePolicy(cookiePolicy);
    }

    @Override public CookieStore getCookieStore() {
        return delegate.get().getCookieStore();
    }

    @Override public Map<String, List<String>> get(
            URI uri, Map<String, List<String>> requestHeaders)
            throws IOException {
        return delegate.get().get(uri, requestHeaders);
    }

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

which gets installed globally

static {
    CookieHandler.setDefault(new DelegatingCookieManager());
}

but has no state and delegate to a

private static final ThreadLocal<CookieManager> delegate =
     new ThreadLocal<CookieManager>();

which gets instantiated in the class where it gets used

private final CookieManager ownCookieManager = new CookieManager();

like

delegate.set(ownCookieManager);
doRequest();
maaartinus
  • 44,714
  • 32
  • 161
  • 320