简体   繁体   中英

HtmlUnit CookieManager not sending cookies with the first request

I am trying to simulate a scenario using HtmlUnit 2.15 where cookies would have been saved in a previous session and should be send to the server when a page is requested in a new session. Here is the code for that...

    String url = "http://localhost:55545/";
    String domain = "localhost:55545";

    java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);

    WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
    CookieManager cookieManager = webClient.getCookieManager();
    cookieManager.setCookiesEnabled(true);

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, 1);
    Cookie cookie = new Cookie(domain, "cName", "cValue", "/", cal.getTime(), false);

    cookieManager.addCookie(cookie);
    webClient.setCookieManager(cookieManager);

    HtmlPage page = null;
    try {
        page = webClient.getPage(url);
    } catch (FailingHttpStatusCodeException e) {
        System.err.print(e.toString());
        return;
    } catch (MalformedURLException e) {
        System.err.print(e.toString());
        return;
    } catch (IOException e) {
        System.err.print(e.toString());
        return;
    }

The expected behavior is I should be receiving the cookie "cName" at the server however no cookies are received there. Also verifying the request through a proxy (fiddler) I see that no Cookie header is being sent by the webclient at the first request.

Has anyone been through this? hoping for some advice before I get into debugging HtmlUnit library.

According to https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_cookies port in domain (host name) is not considered while limiting the scope of a cookie. Removing the port from the domain did the trick.

使用此答案 (基本上是自己构建WebRequest ,手动添加Cookies,然后将其传递给WebClient ),因为可能是您的设置(例如,将Spring Test / WebMVC与HtmlUnit一起使用)不会将cookie从一个请求传递给下一个。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM