Search code examples
javacookiessetcookie

Java, let CookieHandler work on only one instance


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.


Solution

  • 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();