是否可以在htmlunit / webclient中设置cookie

时间:2015-11-12 09:03:49

标签: java cookies webclient htmlunit

我有这个代码,但我找不到最佳解决方案。我不知道在cookie方面。这是代码&警告Cookie。

我正在尝试登录网站,之后我使用getPage下载文件,然后将其写入我的目录。

String url = "https://www.frw.co.uk/login";
    final WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_10);

    webClient.getOptions().setRedirectEnabled(true);
    webClient.getOptions().setCssEnabled(false);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setJavaScriptEnabled(true);
    webClient.getCookieManager().setCookiesEnabled(true);
    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);

    try {

        HtmlPage login = webClient.getPage(url);//button.click();

        final HtmlForm form = (HtmlForm) login.getElementById("loginForm");

        form.getInputByName("j_username").setValueAttribute("example@hotmail.com");
        form.getInputByName("j_password").setValueAttribute("examplepassword");

        HtmlPage reslogin = form.getInputsByValue("Login").get(0).click();

        //reslogin = webClient.getPage("https://www.frw.co.uk/excel/download");

        HtmlPage downloadPage = reslogin.getAnchorByText("Download Wine List").click();

        downloadPage = webClient.getPage("https://www.frw.co.uk/excel/download");


        WebResponse response2 = downloadPage.getWebResponse();
        InputStream is = response2.getContentAsStream();
        OutputStream outputStream = new FileOutputStream(new File(fileTarget));

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = is.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        outputStream.flush();
        outputStream.close();

        System.out.println("Cookie "+webClient.getCookieManager().getCookies());

        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
    }

    webClient.closeAllWindows();

警告结果:

WARNING: Invalid cookie header: "Set-Cookie: fixed_external_2276360454_end_user_id=; Domain=.optimizely.com; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=-1". Negative max-age attribute: -1

WARNING: Cookie rejected: "[version: 0][name: end_user_id][value: oeu1447313832962r0.4258916180646556][domain: .2276360454.log.optimizely.com][path: /js][expiry: Sun Nov 09 15:37:28 CST 2025]". Illegal domain attribute "2276360454.log.optimizely.com". Domain of origin: "cdn.optimizely.com"

0 个答案:

没有答案