您好,我是 HtmlUnit 的新手,我在编码方面遇到问题。我无法根据此代码登录,我是否错过了什么?这是我的代码,例如我不想登录该 URL。请检查我的代码,我已经调试了很长时间了。谢谢。我想单元测试登录后是否可以下载excel文件。然后将其写入流。 URL 是实时网站。请问你能帮帮我吗。在下载文件之前,您需要登录,这就是我现在正在做的事情,但无法登录。
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("example@hotmail.com");
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();
最佳答案
也许尝试使用 cookieManager 添加自动重定向
webClient.getOptions().setRedirectEnabled(true);
webClient.getCookieManager().setCookiesEnabled(true);
关于java - HtmlUnit 无法自动登录网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33538918/