如何将HtmlUnit cookie保存到文件?

时间:2010-02-10 14:01:21

标签: java htmlunit

我想将HtmlUnit cookie保存到文件中,然后在下一次运行时加载它们。我怎样才能做到这一点?感谢。

2 个答案:

答案 0 :(得分:22)

    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 :(得分:3)

以上代码仅适用于HtmlUnit(我不批评或任何东西) 即仅以可由HtmlUnit agin读取的格式导出。

这是一个更通用的:(这适用于卷曲)

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创建String。将它们写入文本文件。

适用于卷曲:

curl -b "path to the text file" "website you want to visit using the cookie"

-b也可以用-c更改..检查curl docs ...