问题描述:

Hello I'm new to HtmlUnit, I have a problem on coding for this one. I couldn't login according to this code did I miss something of what? here is my code for example I wan't to login of that URL. Please check my code I'm debugging this long time. Thank you. I want to Unit test if it can download the excel file after logging in. then write it to the stream. the URL is live website. could you help me please. before you can download the file is you need to login that's what I'm working now but could not login.

 String url = "https://www.frw.co.uk/login";

final WebClient webClient = new WebClient(BrowserVersion.CHROME);

webClient.getOptions().setThrowExceptionOnScriptError(false);

webClient.getOptions().setJavaScriptEnabled(true);

try {

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

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

form.getInputByName("j_username").setValueAttribute("[email protected]");

form.getInputByName("j_password").setValueAttribute("examplePassword");

HtmlPage reslogin = form.getInputByValue("Login").click();

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

final HtmlPage p = downloadPage.getPage();

WebResponse response2 = p.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();

} catch (Exception e) {

e.printStackTrace();

}

webClient.closeAllWindows();

网友答案:

maybe try to add automatic redirection with cookieManager

webClient.getOptions().setRedirectEnabled(true);
webClient.getCookieManager().setCookiesEnabled(true);
相关阅读:
Top