Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save HtmlUnit cookies to a file?

Tags:

java

htmlunit

I'd like to save HtmlUnit cookies to a file and on next run load them from that one. How can I do that? Thanks.

like image 733
Fluffy Avatar asked Feb 10 '10 14:02

Fluffy


1 Answers

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();
}
like image 117
Fluffy Avatar answered Oct 19 '22 08:10

Fluffy