由于您尚未发布要调用的网址,因此我只能提供一些提示。
即使HtmlUnit在幕后发挥了很多魔力,您也需要对所有Web技术有基本的了解
从代码看来,登录是基于Ajax完成的;这有一些含义:Ajax需要启用JavaScript(默认为HtmlUnit)
Ajax是异步的-HtmlUnit中的所有操作(例如,单击)都是同步的,这意味着您必须等待ajax调用完成
在您的特殊情况下,ajax调用会通过使用不同的URL(document.location ='main.html')重新加载页面来成功更改页面的内容。因此,您必须刷新页面变量
或在代码中:
try (WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52))
{
webClient.getOptions().setUseInsecureSSL(true);
HtmlPage page = webClient.getPage(url);
String pageContent = page.asText();
System.out.println(pageContent);
HtmlButtonInput button = page.getFirstByXPath("//input[@type = 'button']");
// to make sure you got the right element
System.out.println(button.asXml());
HtmlTextInput name = (HtmlTextInput) page.getElementById("username");
HtmlPasswordInput pwd = (HtmlPasswordInput) page.getElementById("password");
// use type() to simulate typing
name.type(username);
pwd.type(password);
// no need to get the page here because this is still the one the
// button is placed on
button.click();
// wait for ajax to do the job
webClient.waitForBackgroundJavaScript(10000);
// ok hopefully the job is done and the login was successfull
// lets get the current page out of the current window
HtmlPage loggedInPage = (HtmlPage) page.getEnclosingWindow().getTopWindow().getEnclosedPage();
...
// check the result
// you can also write this to a file and open it in a real browser
// maybe the login was failing and there is an error message
// rendered on this page
System.out.println(loggedInPage.asXml());
}
希望能有所帮助。