htmlunit模拟登录

导读:本篇文章讲解 htmlunit模拟登录,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

 使用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("未登录成功");
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/107521.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!