3

How do you specify a cookie policy in htmlunit to accept all cookies?

Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132

2 Answers2

3

Just recreate the whole CookieManager class: Here is source of the class: http://jarvana.com/jarvana/view/net/sourceforge/htmlunit/htmlunit/2.8/htmlunit-2.8-sources.jar!/com/gargoylesoftware/htmlunit/CookieManager.java?format=ok

Now lookup this method public synchronized Set<Cookie> getCookies(final URL url) in there you find this:

   public static final String HTMLUNIT_COOKIE_POLICY = CookiePolicy.BROWSER_COMPATIBILITY; //default
   final CookieSpec spec = registry_.getCookieSpec(HTMLUNIT_COOKIE_POLICY);

   for (final org.apache.http.cookie.Cookie cookie : all) {
        if (spec.match(cookie, cookieOrigin)) {
            matches.add(cookie);
        }
    }

Remote the specs matching statement if (spec.match(cookie, cookieOrigin)) you you should accept all cookies regardless on policy. And/or you can work up ACCEPT_ALL_COOKIES flag and by pass the specs matching if that is the policy indicated in the configuration.

MatBanik
  • 26,356
  • 39
  • 116
  • 178
2

Some solutions with source code modifications.

  1. You can simply remove cookieSpec.validate(cookie, cookieOrigin); line from org.apache.http.client.protocol.ResponseProcessCookies in httpClient

  2. In htmlUnit you can create your own strategy and use it in com.gargoylesoftware.htmlunit.CookieManager instead of

      public static final String HTMLUNIT_COOKIE_POLICY = CookiePolicy.BROWSER_COMPATIBILITY;
      ...
      final CookieSpec spec = registry_.getCookieSpec(HTMLUNIT_COOKIE_POLICY);
    

    Optionally it should depends from constructor parameter of CookieManager but authors doesn't think so)

     /**
      * HtmlUnit's cookie policy is to be browser-compatible. Code which requires access to
      * HtmlUnit's cookie policy should use this constant, rather than making assumptions and using
      * one of the HttpClient {@link CookiePolicy} constants directly.
      */
    

    So if you want implement your own Cookie strategy or deal with cases where CookiePolicy.BROWSER_COMPATIBILITY isn't browser capability you should modify code.

Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132