I am using java.net.CookieManager & java.net.CookieHandler to track cookies. I need to remove one but keep all others. The problem is that the List return from the using cookieManger.getCookieStore().getCookies() is unmodifiable and therefore throws an exception when I attempt to remove the cookie.
Here is the code regarding cookies:
public HttpProxy(String host, String port) {
cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
//other irrelevant code
}
private CookieManager cookieManager;
public void deleteGameCookie() {
CookieStore cookieStore = cookieManager.getCookieStore();
List<HttpCookie> cookieList = cookieStore.getCookies();
HttpCookie temp = null;
// iterate HttpCookie object
for (HttpCookie cookie : cookieList) {
try {
String name = URLDecoder.decode(cookie.getName().replace("+", "%2B"), "UTF-8").replace("%2B", "+");
if(name.equals("catan.game")) {
System.out.println("catan.game cookie found");
temp = cookie;
}
} catch (UnsupportedEncodingException e) {
//System.out.println("Error decoding cookie... bummer...");
e.printStackTrace();
}
}
cookieList.remove(temp);
}
Is there a way around this or a better way to do this?
I found a similar question about unmodifiable collections here but it hasn't been answered. Thanks for your help!
you probably want to use one of the remove methods on cookie store not try and work with the list directly. see:
http://docs.oracle.com/javase/7/docs/api/java/net/CookieStore.html