简体   繁体   English

HtmlUnit CookieManager不通过第一个请求发送cookie

[英]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. 我正在尝试使用HtmlUnit 2.15模拟一个场景,其中cookie将被保存在上一个会话中,并且在新会话中请求页面时应将其发送到服务器。 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. 预期的行为是我应该在服务器上收到cookie“ cName”,但是在那里没有收到cookie。 Also verifying the request through a proxy (fiddler) I see that no Cookie header is being sent by the webclient at the first request. 同样通过代理(提琴手)验证请求,我发现在第一个请求时,webclient没有发送Cookie头。

Has anyone been through this? 有人经历过这个吗? hoping for some advice before I get into debugging HtmlUnit library. 希望在我调试HtmlUnit库之前获得一些建议。

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. 根据https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_cookies ,在限制Cookie范围的同时,不考虑域(主机名)中的端口。 Removing the port from the domain did the trick. 从域中删除端口可以解决问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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