我想将HtmlUnit的Cookies保存到一个文件中,并在下一次运行时从该文件中加载它们。我该如何做?谢谢。
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();
}
以上代码仅适用于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() + ";");
}
curl -b "path to the text file" "website you want to visit using the cookie"
-b 也可以用 -c 替换。请查看 curl 文档。
wc.getCookieManager().addCookie(i.next());
不会导致Cookies在下一个请求中被发送(检查了 com.gargoylesoftware.htmlunit.Webclient 和 com.gargoylesoftware.htmlunit.WebRequest 的代码,CookieManager 并未被使用)。我只能使用此答案来通过新请求传递Cookies(即手动构建 WebRequest)。 - user2039709ObjectOutput
is an interface, third statement from end needs to beObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("cookie.file"));
- mrzzmr