如何遍历所有cookie并删除它们的Java

时间:2019-03-14 13:37:08

标签: java cookies

声明cookie变量

private List<String> cookies;

收集cookie

    setCookies(httpConn.getHeaderFields().get("Set-Cookie"));

使用方法调用Cookie:

public List<String> getCookies() {
    return cookies;
}

设置Cookie的方法:

public void setCookies(List<String> cookies) {
    this.cookies = cookies;
}

在构造函数中重置cookie

public void Reset() {
    System.out.println("start clear and set....................");
    if (HttpClient.getCookies() != null) {
        for (Iterator iterator = HttpClient.getCookies().iterator(); iterator.hasNext();) {
            Object next = iterator.next();
            System.out.println(next);
            if (next != null) {

            iterator.remove();
            System.out.println("clearing....................");
            }
        }
    }
    System.out.println("cleared ,setting....................");
}

输出

start clear and set....................
PHPSESSID=vkqcf64f79bptfvf9e8volea23; path=/
start clear and set....................
_smasher_session=bb09471bbf02ad62a937c1cb75b7bf6c; domain=domain.com; path=/

我如何迭代和清除所有cookie?

1 个答案:

答案 0 :(得分:1)

只需清除列表即可,而不是反复进行删除

setCookies(Collections.emptyList());

HttpClient.getCookies()可能不会每次都返回相同的对象,因此,如果清除一个实例,则可能无法清除使用setCookies设置的初始实例。