首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android-WebView的onReceivedHttpAuthRequest()不会再次调用

Android-WebView的onReceivedHttpAuthRequest()不会再次调用
EN

Stack Overflow用户
提问于 2013-12-05 19:54:04
回答 3查看 6.5K关注 0票数 10

我正在使用一个基于webview的应用程序,其中我在webview中呈现了一个url。Url具有HTTP身份验证。

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

代码语言:javascript
复制
@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()再也不会被调用。

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

代码语言:javascript
复制
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数据库:

代码语言:javascript
复制
BrowserActivity.this.deleteDatabase("webview.db");
BrowserActivity.this.deleteDatabase("webviewCache.db");

我不知道为什么会发生这种事。有没有人能帮我这个忙。至少在为什么不调用onReceivedHttpAuthRequest()这个问题上?

EN

回答 3

Stack Overflow用户

发布于 2017-02-15 17:31:01

  1. 在加载url之前,请在http标头中设置授权信息

Map extraHeaders = HashMap<>();extraHeaders.put("Authorization",“TlRM”);//值随意设置。

webView.loadUrl(url,extraHeaders);

  • in WebViewClient

@Override public void onReceivedHttpAuthRequest(WebView视图,HttpAuthHandler处理程序,

String主机,String realm) {view.loadUrl( url );//重新加载url。

Handler.proceed(帐户,密码);}

  • 我解决了这个问题,但我的英语说得不是很好。希望它能帮助你。
票数 3
EN

Stack Overflow用户

发布于 2015-02-23 13:42:00

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

代码语言:javascript
复制
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();
    }
票数 0
EN

Stack Overflow用户

发布于 2020-08-05 07:06:59

我使用"Authorization“头而不是onReceivedHttpAuthRequest()来解决它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20399339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档