How to save HtmlUnit cookies to a file?

前端 未结 2 724
眼角桃花
眼角桃花 2020-12-30 09:56

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.

2条回答
  •  天涯浪人
    2020-12-30 10:19

        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 cookies = (Set) in.readObject();
            in.close();
    
            WebClient wc = new WebClient();
    
            Iterator 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();
        }
    

提交回复
热议问题