9

I needed to connect to a website from multiple threads simultaneously using HttpURLConnection, but use different cookies for each connection. Since Java only supports setting a global CookieManager, I've implemented the following hack.

Instead of calling CookieHandler.setDefault(new CookieManager()), I've implemented a custom CookieHandler which uses a different CookieStore instance for every thread, which is cleared after each request.

I've created class called SessionCookieManager based on the source code of CookieManager.

The cookieJar member variable was removed, and its usage has been replaced by getCookieStore().

The following code was added:

public class SessionCookieManager extends CookieHandler {
    private final static SessionCookieManager ms_instance = new SessionCookieManager();

    public static SessionCookieManager getInstance() {
        return ms_instance;
    }

    private final static ThreadLocal<CookieStore> ms_cookieJars = new ThreadLocal<CookieStore>() {
        @Override
        protected synchronized CookieStore initialValue() { return new sun.net.www.protocol.http.InMemoryCookieStore(); }
    };

    public void clear() {
        getCookieStore().removeAll();
    }

    public CookieStore getCookieStore() {
        return ms_cookieJars.get();
    }

Before the first request, the custom CookieManager is set as the global default CookieHandler:

CookieHandler.setDefault(SessionCookieManager.getInstance());

After every request, the current thread's CookieStore is cleared:

try {
    ...
} finally {
    SessionCookieManager.getInstance().clear();
}
nivs
  • 1,783
  • 1
  • 11
  • 13
  • Is this a question? It sounds like you are listing what you've done. Are you asking if this is a good idea? I think it is not. This code is not thread-safe. Only locking will ensure that each thread sees only its intended CookieStore. I recommend using HttpClient instead if you can. You might consider posting a code review like this here http://codereview.stackexchange.com/ – John Watts Jun 10 '12 at 11:58
  • Agreed, but why do you think this code not thread-safe? – nivs Jun 11 '12 at 12:08
  • I misread it. I don't see any threading problems. The only negative I see is that you had to reference a Sun internal class. Are you having a problem with it? – John Watts Jun 12 '12 at 02:11
  • I created a complete HowTo based on this @ http://stackoverflow.com/questions/16305486/cookiemanager-for-multiple-threads – Wurstbro May 04 '13 at 13:48

1 Answers1

1

One work around would be to use Cookie header directly instead sending the cookie. See cookie header here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa384321(v=vs.85).aspx which you can change every call.

Cookie: <name>=<value> [;<name>=<value>]...
Dheerendra Kulkarni
  • 2,608
  • 1
  • 13
  • 16