Skip to content Skip to sidebar Skip to footer

How To Save Htmlunit Cookies To A File?

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.

Solution 1:

publicstaticvoidmain(String[] args)throws Exception {
    LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    
    Filefile=newFile("cookie.file");
    ObjectInputStreamin=newObjectInputStream(newFileInputStream(file));
    Set<Cookie> cookies = (Set<Cookie>) in.readObject();
    in.close();
    
    WebClientwc=newWebClient();
    
    Iterator<Cookie> i = cookies.iterator();
    while (i.hasNext()) {
        wc.getCookieManager().addCookie(i.next());
    }
    
    HtmlPagep= wc.getPage("http://google.com");
    
    ObjectOutputout=newObjectOutputStream(newFileOutputStream("cookie.file"));
    out.writeObject(wc.getCookieManager().getCookies());
    out.close();
}

Solution 2:

The above code works only with HtmlUnit (Im not criticizing or anything) i.e. exports only in a format that can be read by HtmlUnit agin.

Here is a more generic one: (This works with 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() + ";");
    }

Now, Make String out of those println(s) in the for loop. write them to a text file.

works with curl :

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

-b can be changed with -c too.. check curl docs...

Post a Comment for "How To Save Htmlunit Cookies To A File?"