如何在WebView中处理基本身份验证

Kyl*_*yle 14 android android-webview

我创建了一个加载WebView的应用程序.要登录,网站需要基本身份验证.当我尝试通过默认浏览器访问网站时,我弹出一个弹出框提示我输入我的用户名和密码.

如果我尝试通过我的应用程序访问该网站,我收到错误401并且没有弹出.我想知道是否有人可以帮助我?

Saa*_*ooq 27

我认为比Patrick描述的更优雅的解决方案是使用onReceivedHttpAuthRequestWebViewClient 的方法,如下所述:http://www.mail-archive.com/android-developers@googlegroups.com/msg30468.html

@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
    handler.proceed("username", "password");
}
Run Code Online (Sandbox Code Playgroud)

  • 对于上面的代码,您必须删除 super. onReceivedHttpAuthRequest()。否则它会调用handle.cancel,这将使您的代码无法工作。 (4认同)

Pat*_*oos 9

该网站需要身份验证.

首先你对错误作出反应:

webview.setWebViewClient(new WebViewClient() {
   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
     if (errorCode == 401) {
         // show alert to enter username and password
         // then when those are entered in the alert,
         //     set it through the setHttpAuthUsernamePassword(...) shown below
         //     and then reload the site
     }
   }
 });
Run Code Online (Sandbox Code Playgroud)

使用此功能设置用户和密码: WebView.setHttpAuthUsernamePassword()

webview.setHttpAuthUsernamePassword(host, realm, username, password);
Run Code Online (Sandbox Code Playgroud)

一切都是字符串.有关主机和领域的含义的更多信息,请参阅上面的链接.

此处找到解决方案:为WebView提供一些基本身份验证凭据?


Noo*_*bTW 8

public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
     handler.proceed("USERNAME", "PASSWORD");
}
Run Code Online (Sandbox Code Playgroud)

我认为它对WebView上的401错误很有帮助.

  • 我尝试过这种方法,结果一团糟.我非常不鼓励使用这种方法.如果您提供了错误的用户名或密码,则身份验证将失败,并且webview会继续重试身份验证.这是在我的服务器上创建重复的api调用,最终导致服务器崩溃.您可以考虑使用counter和stopLoading()方法来避免无限循环. (4认同)