2010-02-10 14 views

Respuesta

22
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(); 
    } 
+1

Me gustaría que más personas comentaron que tú. Sencillo. Contesta la pregunta. Brillante. Muchas gracias! – David

+0

Con htmlunit 2.23 'wc.getCookieManager(). AddCookie (i.next());' no provocó que las cookies se enviaran en la siguiente solicitud (verificó el código de _com.gargoylesoftware.htmlunit.Webclient_ y _com.gargoylesoftware. htmlunit.WebRequest_, CookieManager no se usa allí). Solo pude usar [esta respuesta] (http://stackoverflow.com/a/36155793/2039709) para pasar Cookies con una nueva Solicitud (es decir, crear la WebRequest manualmente) – user2039709

3

El código anterior funciona sólo con HtmlUnit (Im no criticar ni nada) solamente es decir, las exportaciones en un formato que puede ser leído por HtmlUnit Agin.

Aquí está una más genérica uno: (Esto funciona con 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() + ";"); 
    } 

Ahora, Prefijo para salir de esos println (s) en el bucle. escríbelas en un archivo de texto.

obras con rizo:

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

-b se puede cambiar con -c también .. comprobar documentos enrollamiento ...