Java, let CookieHandler work on only one instance

萝らか妹 提交于 2020-01-14 10:36:13

问题


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.

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/4543328/java-let-cookiehandler-work-on-only-one-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!