在Android WebView HTTP Authentification中停止重试

时间:2016-11-11 09:57:14

标签: android webview raspberry-pi3 http-authentication

我的Android应用程序中有一个WebView,它从我的覆盆子pi加载一个网页。此网页受基本身份验证保护。

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
        handler.proceed(user, pass);
    }

    @Override
    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        super.onReceivedHttpError(view, request, errorResponse);
// I'm always landing here if authentification fails.
    }
});

webView.loadUrl(protocol + "://" + hostname + ":" + port);

如果身份验证失败,我该如何停止重试?如果我不停止此操作,应用会每秒发送一次请求,直到我关闭应用。

感谢。

1 个答案:

答案 0 :(得分:0)

  webView.setWebViewClient(new WebViewClient() {
        int tries = 0;

        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
            handler.proceed(user, pass);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);

            if (tries > 1) {
                webView.destroy();
                Toast.makeText(getApplicationContext(), errorResponse.getStatusCode() + ": "
                        + errorResponse.getReasonPhrase(), Toast.LENGTH_LONG).show();
            }
            tries++;
        }
    });

    webView.loadUrl(protocol + "://" + hostname + ":" + port);