如何使用HttpURLConnection和Java中的CookieManager为每个连接使用不同的cookie [英] How to use different cookies for each connection using HttpURLConnection and the CookieManager in Java

查看:280
本文介绍了如何使用HttpURLConnection和Java中的CookieManager为每个连接使用不同的cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用HttpURLConnection同时从多个主题连接到一个网站,但每个连接使用不同的Cookie。因为Java只支持设置一个全局CookieManager,所以我实现了下面的hack。

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.

而不是调用 CookieHandler.setDefault(new CookieManager ,我实现了一个自定义 CookieHandler ,它为每个线程使用不同的 CookieStore

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.

我已经创建了 SessionCookieManager 类,基于源代码 CookieManager

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

cookieJar 成员变量已删除,并且其使用已被 getCookieStore()替换。

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

添加了以下代码:

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

在第一个请求之前,自定义 CookieManager 设置为全局默认 CookieHandler

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

CookieHandler.setDefault(SessionCookieManager.getInstance());

每次请求后,当前线程的 CookieStore 已清除:

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

try {
    ...
} finally {
    SessionCookieManager.getInstance().clear();
}


推荐答案

直接使用Cookie头,而不是发送cookie。
请参阅cookie标头: https://msdn.microsoft.com/en-us/library/windows/desktop/aa384321(v = vs.85).aspx ,您可以更改每次通话。

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>]...

这篇关于如何使用HttpURLConnection和Java中的CookieManager为每个连接使用不同的cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆