6

我正在尝试使用 HtmlUnit 登录到我的本地 wordpress 网站,但它似乎有 cookie 问题。

那就是代码的开头:

WebClient webClient = new WebClient();
HtmlPage loginPage = webClient.getPage("http://localhost/flowersWp/wp-admin");
HtmlForm form = loginPage.getFormByName("loginform");

这就是我在日志中得到的。有人有想法吗?谢谢。

2010 年 11 月 27 日下午 12:43:35 org.apache.http.client.protocol.ResponseProcessCookies processCookies 警告:Cookie 被拒绝:“[版本:0][名称:wordpress_2418eeb845ebfb96f6f1a71ab8c5625a][值:+][域:本地主机][路径:/flowersWp/wp-admin][有效期:2009 年 11 月 27 日星期五 12:43:35 IST]"。非法路径属性“/flowersWp/wp-admin”。来源路径:“/flowersWp/wp-login.php”

4

2 回答 2

7

WebClient 使用的是 apache httpclient,所以是 HttpClient 的问题。

根据我的经验,它与重定向有关。我已经使用 HttpClient 解决了这个问题并注册了我自己的 cookie 支持:

  // Create a local instance of cookie store
  CookieStore cookieStore = new BasicCookieStore();

  // Bind custom cookie store to the local context
  httpclient.setCookieStore(cookieStore);
  CookieSpecFactory csf = new CookieSpecFactory() {
      public CookieSpec newInstance(HttpParams params) {
          return new BrowserCompatSpec() {
              @Override
              public void validate(Cookie cookie, CookieOrigin origin)
              throws MalformedCookieException {
                // Oh, I am easy.
                // Allow all cookies
                log.debug("custom validate");
              }
          };
      }
  };
  httpclient.getCookieSpecs().register("easy", csf);
  httpclient.getParams().setParameter(
       ClientPNames.COOKIE_POLICY, "easy"); 

好吧,在 HtmlUnit 中我无法直接访问 httpclient,但我正在考虑更改其源代码,因为我需要连接到带有 JavaScript 支持的 wordpress。

于 2010-12-06T08:04:58.023 回答
0

我必须注意,在 HttpClient 4+ 中,我必须执行以下操作:

        CookieSpecProvider csf = new CookieSpecProvider() {
            @Override
            public CookieSpec create(HttpContext context)
            {
                return new BrowserCompatSpec() {
                    @Override
                    public void validate(Cookie cookie, CookieOrigin origin)
                        throws MalformedCookieException
                    {
                        // Allow all cookies
                    }
                };
            }
        };

        RequestConfig requestConfig = RequestConfig.custom()
            .setCookieSpec("easy")
            .build();

        httpclient = HttpClients
            .custom()
//          .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
            .setDefaultCookieStore(cookieStore)
            .setDefaultCookieSpecRegistry(RegistryBuilder.<CookieSpecProvider>create()
                                              .register(CookieSpecs.BEST_MATCH, csf)
                                              .register(CookieSpecs.BROWSER_COMPATIBILITY, csf)
                                              .register("easy", csf).build())
            .setDefaultRequestConfig(requestConfig)
//          .setSSLSocketFactory(sslsf)
            .build();
于 2015-01-12T13:21:52.290 回答