【问题标题】:Android-WebView's onReceivedHttpAuthRequest() not called againAndroid-WebView 的 onReceivedHttpAuthRequest() 不再调用
【发布时间】:2013-12-22 08:30:37
【问题描述】:

我正在使用基于 webview 的应用程序,我在 webview 中呈现 url。该 URL 具有 HTTP 身份验证。

当我第一次启动 url 时,它的 onReceivedHttpAuthRequest() 被调用,我显示一个对话框让用户输入身份验证凭据,即身份验证用户名和密码。

@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
        final WebView mView = view;
        final HttpAuthHandler mHandler = handler;

        final EditText usernameInput = new EditText(mActivity);
        usernameInput.setHint("Username");

        final EditText passwordInput = new EditText(mActivity);
        passwordInput.setHint("Password");
        passwordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

        LinearLayout ll = new LinearLayout(mActivity);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.addView(usernameInput);
        ll.addView(passwordInput);

        Builder authDialog = new AlertDialog
                .Builder(mActivity)
                .setTitle("Authentication")
                .setView(ll)
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        mHandler.proceed(usernameInput.getText().toString(), passwordInput.getText().toString());
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                        mView.stopLoading();
                        onLoadListener.onAuthCancel((MyWebView)mView, mTitleTextView);
                    }
                });

        if(view!=null)
            authDialog.show();

    }

在提交请求时进行顺利并加载 url。但是在我使用后退按钮(不在后台发送)退出应用程序后,如果我再次启动它并 tru 加载相同的 url,它会直接加载 url 而不会要求再次调用 onReceivedHttpAuthRequest() 的凭据。

我还在使用以下代码清除应用退出时的凭据:

WebViewDatabase webDB = WebViewDatabase.getInstance(BrowserActivity.this);
    if(webDB!=null){
        if(webDB.hasFormData())
            webDB.clearFormData();
        if(webDB.hasUsernamePassword())
            webDB.clearUsernamePassword();
        if(webDB.hasHttpAuthUsernamePassword())
            webDB.clearHttpAuthUsernamePassword();
    }
webView.clearCache(true);

我还要清除所有 webview 缓存、cookie 和应用程序的缓存目录和 webview 数据库:

BrowserActivity.this.deleteDatabase("webview.db");
BrowserActivity.this.deleteDatabase("webviewCache.db");

我不知道为什么会这样。有没有人可以帮助我解决这个问题。 至少在为什么不调用 onReceivedHttpAuthRequest() 的问题上?

【问题讨论】:

  • 您确定清除保存的用户名/密码的代码正在执行吗?
  • 是的,它被执行了。此外,当我强制停止应用程序然后启动时,它会要求身份验证。
  • 好的,所以听起来只有当您使用后退按钮时不起作用?究竟什么时候运行清除数据库的代码?
  • 1.清除 Webview 缓存。 2. 删除数据库。 3.清除cookies。 4.删除缓存目录
  • @Thushara,还没有,我现在已经更改了功能。但仍在寻找相同的东西。

标签: android webview android-webview basic-authentication webviewclient


【解决方案1】:
  1. 在加载url之前,在http headers中设置授权信息

    Map extraHeaders = new HashMap(); extraHeaders.put("Authorization", "TlRM");//值随便设置。
    webView.loadUrl(url, extraHeaders);

  2. 在 WebViewClient 中

    @覆盖 public void onReceivedHttpAuthRequest(WebView 视图,HttpAuthHandler 处理程序,
    字符串主机,字符串领域){ view.loadUrl(url);//重新加载url。
    handler.proceed(帐户,密码); }

  3. 我解决了这个问题,但我的英语说得不太好。 希望对你有帮助。

【讨论】:

    【解决方案2】:

    这样做的原因是 webview 存储了以前的连接 cookie。所以我们需要手动清除它们并为当前 url 存储新的 cookie 数据。我们可以这样做。

    HttpURLConnection connection = null;
        try {
            URL urls = new URL(url);
            String authStr = "";
            if (!params.isEmpty()) {
                authStr = params.get(0).getValue() + ":"
                        + params.get(1).getValue();
            }
    
            String authEncoded = Base64.encodeBytes(authStr.getBytes());
    
            connection = (HttpURLConnection) urls
                    .openConnection();
            connection.setConnectTimeout(5100);
            connection.setReadTimeout(5200);
            connection.setDoOutput(false);
            connection.setRequestProperty("Authorization", "Basic "
                    + authEncoded);
            CookieManager cookieManager = CookieManager.getInstance();
            String cookie = cookieManager.getCookie(connection.getURL().toString());
            if (cookie != null) {
                connection.setRequestProperty("Cookie", cookie);
            }
            connection.connect();
    
            responseCode = connection.getResponseCode();
            InputStream content = connection.getInputStream();
            response = convertStreamToString(content);
            content.close();
    
            // Get cookies from responses and save into the cookie manager. session is created only in rest call url
            List<String> cookieList = connection.getHeaderFields().get("Set-Cookie");
            if (cookieList != null) {
                for (String cookieTemp : cookieList) {
                    cookieManager.setCookie(connection.getURL().toString(), cookieTemp);
                }
            }
    
        }catch (SocketTimeoutException es){
            response = ConnectionStatus.TIME_OUT.name();
        } catch (Exception e) {
            response = e.getMessage();
            e.printStackTrace();
        }
        finally {
            connection.disconnect();
        }
    

    【讨论】:

      【解决方案3】:

      我使用“授权”标头而不是使用 onReceivedHttpAuthRequest() 解决了它

      【讨论】:

      • 即使在添加之后我也无法仅接收 onhttprequestmethod
      猜你喜欢
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多