![](/img/trans.png)
[英]Should HttpURLConnection with CookieManager automatically handle session cookies?
[英]How to use different cookies for each connection using HttpURLConnection and the CookieManager in Java
我需要使用HttpURLConnection從多個線程同時連接到網站,但是每個連接使用不同的cookie。 由於Java僅支持設置全局CookieManager,因此我實現了以下技巧。
我沒有調用CookieHandler.setDefault(new CookieManager())
,而是實現了一個自定義CookieHandler
,該自定義CookieHandler
為每個線程使用一個不同的CookieStore
實例,該實例在每次請求后都會清除。
我已經基於CookieManager
的源代碼創建了一個名為SessionCookieManager
的類。
cookieJar
成員變量已刪除,其用法已由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
:
CookieHandler.setDefault(SessionCookieManager.getInstance());
每次請求后,都會清除當前線程的CookieStore
:
try {
...
} finally {
SessionCookieManager.getInstance().clear();
}
一種解決方法是直接使用Cookie標頭,而不是發送Cookie。 在此處查看Cookie標頭: https : //msdn.microsoft.com/zh-cn/library/windows/desktop/aa384321(v=vs.85).aspx ,您可以更改每個呼叫。
Cookie: <name>=<value> [;<name>=<value>]...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.