如何将HtmlUnit cookie保存到文件?

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

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 cookies = (Set) in.readObject(); in.close(); WebClient wc = new WebClient(); Iterator 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(); } 

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

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

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

现在,在for循环中使用那些println创建String。 将它们写入文本文件。

适用于curl:

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

-b也可以用-c更改.. check curl docs …