HtmlUnit Cookieをファイルに保存し、次回の実行時にその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(批判などではありません)でのみ機能します。つまり、HtmlUnitaginで読み取れる形式でのみエクスポートします。
より一般的なものは次のとおりです:(これは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から文字列を作成します。それらをテキストファイルに書き込みます。
カールで動作します:
curl -b "path to the text file" "website you want to visit using the cookie"
-bも-cで変更できます。curlドキュメントを確認してください。
于 2013-05-13T07:31:29.220 に答える