我想将 HtmlUnit cookie 保存到一个文件中,并在下次运行时从该文件中加载它们。我怎样才能做到这一点?谢谢。
问问题
9198 次
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();
}
于 2010-02-10T17:00:12.073 回答
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 文档...
于 2013-05-13T07:31:29.220 回答