Android-WebView路由登录192.168.1.1

由于项目需求制做路由器的登录,有的路由可以直接打开网页登录,有的是打开的登录窗

我们的路由是打开的登录窗口,我在自己写的时候用WebView打不开登录窗

在网上搜索的答案是
WebView.setHttpAuthUsernamePassword(host, realm, username, password)
WebView增加WebChromeClient重写onJsAlert
发现以上办法都不能解决问题
 
用浏览器打开的时候会弹出登录框,当我用Android WebView登录的时候提示登录失败
打不开登录框,一开始我以为是js生成的弹出框
试验给WebView setWebChromeClient 
重写 WebChromeClient 中的
public boolean onJsAlert(WebView view, String url, String message, JsResult result) 
public boolean onJsConfirm(WebView view, String url, String message, JsResult result)
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result)
public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result)
public boolean onJsTimeout()
发现以上方法没有一个执行到了
然后我在对比火狐,IE,Google Chrome感觉是浏览器自己做的
浏览器打开的时候会提示输入用户名和密码
 
发现WebViewClient中有一个方法 onReceivedHttpAuthRequest
然后查看源码
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { 
        handler.cancel();
}
发现是直接调用的 handler.cancel();
给WebView增加WebViewClient 重写 onReceivedHttpAuthRequest 将此方法置空
发现登录的时候会停止在一个空白页面,等待处理,并没有像开始直接打开的时候提示登录失败
 
然后查看onReceivedHttpAuthRequest中的参数有一个HttpAuthHandler 
源码默认是调用的cancel() 发现还有一个方法 proceed(String username, String password)
 
然后在重写 onReceivedHttpAuthRequest时
public void onReceivedHttpAuthRequest(WebView view,  HttpAuthHandler handler, String host, String realm) { 
        handler.proceed("admin", "admin");
} // PS: admin 是我路由器默认的帐号和密码

然后就登录进去了我的路由器,问题到这里已经解决

onReceivedHttpAuthRequest这个方法也是在主线程中的,可以在这里制做自己的登录窗口

原文地址:https://www.cnblogs.com/smile365/p/4130983.html