如何将HtmlUnit的cookies保存到文件中?

13

我想将HtmlUnit的Cookies保存到一个文件中,并在下一次运行时从该文件中加载它们。我该如何做?谢谢。

2个回答

24
public static void main(String[] args) throws Exception {
    LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    
    File file = new File("cookie.file");
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
    Set<Cookie> cookies = (Set<Cookie>) in.readObject();
    in.close();
    
    WebClient wc = new WebClient();
    
    Iterator<Cookie> i = cookies.iterator();
    while (i.hasNext()) {
        wc.getCookieManager().addCookie(i.next());
    }
    
    HtmlPage p = wc.getPage("http://google.com");
    
    ObjectOutput out = new ObjectOutputStream(new FileOutputStream("cookie.file"));
    out.writeObject(wc.getCookieManager().getCookies());
    out.close();
}

1
我希望更多的人像你一样评论。简单明了,回答问题,非常出色。非常感谢! - David
使用htmlunit 2.23版本时,wc.getCookieManager().addCookie(i.next()); 不会导致Cookies在下一个请求中被发送(检查了 com.gargoylesoftware.htmlunit.Webclientcom.gargoylesoftware.htmlunit.WebRequest 的代码,CookieManager 并未被使用)。我只能使用此答案来通过新请求传递Cookies(即手动构建 WebRequest)。 - user2039709
ObjectOutput is an interface, third statement from end needs to be ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("cookie.file")); - mrzzmr

3

以上代码仅适用于HtmlUnit (我并没有批评任何东西), 即只能导出可以被HtmlUnit再次读取的格式。

以下是一种更通用的方法: (这适用于curl)

CookieManager CM = WC.getCookieManager(); //WC = Your WebClient's name
    Set<Cookie> set = CM.getCookies();
    for(Cookie tempck : set)    {
        System.out.println("Set-Cookie: " + tempck.getName()+"="+tempck.getValue() + "; " + "path=" + tempck.getPath() + ";");
    }

现在,将for循环中的println(s)转换为字符串,并将其写入文本文件。
可以使用curl运行此操作:
curl -b "path to the text file" "website you want to visit using the cookie"

-b 也可以用 -c 替换。请查看 curl 文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接