使用htmlunit登录的原因是前端有加密控件,所以输入密码的时候使用的是键盘输入
WebClient webClient = new WebClient(BrowserVersion.FIREFOX);
webClient.getOptions().setCssEnabled(false);//关闭css
webClient.getOptions().setJavaScriptEnabled(true);//开启js
webClient.getOptions().setRedirectEnabled(true);//重定向
webClient.getOptions().setThrowExceptionOnScriptError(false);//关闭js报错
webClient.getOptions().setTimeout(50000);//超时时间
webClient.getCookieManager().setCookiesEnabled(true);//允许cookie
webClient.setAjaxController(new NicelyResynchronizingAjaxController());//设置支持AJAX
HtmlPage page = webClient.getPage("url");
HtmlForm loginForm = page.getFormByName("loginForm");
//输入账号
HtmlInput userName = loginForm.getInputByName("userName");
aName.setValueAttribute("18888888888");
//点击控件后键盘输入密码
HtmlElement pwd = page.getHtmlElementById("pwd");
pwd.click();
pwd.type((char) KeyboardEvent.DOM_VK_6);
pwd.type((char) KeyboardEvent.DOM_VK_6);
pwd.type((char) KeyboardEvent.DOM_VK_6);
//此处获取cookie,原本打算拿到cookie后发请求打码的,但是总是验证码出错。只能保存到本地
CookieManager cookieManager = webClient.getCookieManager();
//Map<String, String> headers = new HashMap<>();
Cookie cookie = cookieManager.getCookie("JSESSIONID");
COOKIE =cookie.toString();
//headers.put("Cookie", cookie.toString());
//Map<String, String> dama = xxx.xxx(HTTPUtils.xxx("url", headers, ""));
//HtmlInput captch = loginForm.getInputByName("captch");
//captch.setValueAttribute(dama.get("captch"));
//输入验证码,验证码保存在本地
File file = File.createTempFile(DateUtils.format(new Date(),"yyyyMMdd_HHmmss") + new Random().nextInt(100), ".png");
HtmlImage img = (HtmlImage) page.getElementById("img");
img.saveAs(file);
Map<String, String> xxx = xxx.xxx(FileUtils.readFileToByteArray(file));
HtmlInput code = loginForm.getInputByName("code");
code.setValueAttribute(xxx.get("value"));
System.err.println(file.delete());
//选择checkBox
List<HtmlRadioButtonInput> radios = loginForm.getRadioButtonsByName("radio");
for (HtmlRadioButtonInput r : radios){
if (r.getDefaultValue().equals("xxx")){
r.click();
break;
}
//点击登录 button没有name属性
HtmlElement submitButton = page.getHtmlElementById("submitButton");
submitButton.click();
//等待JS驱动dom完成获得还原后的网页
//webClient.waitForBackgroundJavaScript(30000);
//无法自动跳转,主动去跳转页面查看是否登录成功(我这里怎么搞都没法自动跳转,就这么处理了)
HtmlPage page1 = webClient.getPage("url1");
webClient.close();
if (page1.getUrl().equals(page.getUrl())){
LogUtils.error("未登录成功");
}