Java HtmlUnit - can't login to wordpress

谁都会走 提交于 2019-11-29 04:38:42

WebClient is using apache httpclient, so it is an HttpClient problem.

From my experience, it has to do with redirections. I've gotten rid of this problem using HttpClient and registering my own cookie support:

  // 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"); 

Well, in HtmlUnit I have no direct access to httpclient, but I'm thinking of changing its source code to do so, as I need to connect to wordpress with JavaScript support.

I must note that in HttpClient 4+, I had to do the following:

        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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!