【问题标题】:HTTP status code webview android, WebViewClientHTTP状态码webview android, WebViewClient
【发布时间】:2018-01-21 09:54:20
【问题描述】:

所以我阅读了许多关于 SO 的问题,但仍然想问这个问题。我的片段中有一个网络视图。我正在调用一个 url 并想知道 HTTP 状态代码(成功或失败)。我从 WebViewClient 类扩展了一个类,下面是相同的 sn-p。

我遇到了这种方法:

@Override
    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        super.onReceivedHttpError(view, request, errorResponse);
        if (Build.VERSION.SDK_INT >= 21){
            Log.e(LOG_TAG, "HTTP error code : "+errorResponse.getStatusCode());
        }

        webviewActions.onWebViewReceivedHttpError(errorResponse);
    }

如你所见,我已勾选

Build.VERSION.SDK_INT >= 21 自从 errorResponse.getStatusCode()

自 API 21 起支持该方法。但如果我想要在 API 21 之前获得此状态码怎么办?然后我发现下面的代码:

@SuppressWarnings("deprecation")
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        Toast.makeText(context, "error code : "+errorCode+ "\n description : "+description, Toast.LENGTH_SHORT).show();
        if (errorCode == -2){
            Log.e(LOG_TAG, "error code : "+errorCode+ "\n description : "+description);
            redirectToHostNameUrl();
        }
    }

此方法已弃用,因此我不得不使用注释。在这里,在“errorCode”中,我得到 HTTP 代码 404 的值 -2。我将此作为解决方法。但是,如果我想避免使用这种已弃用的方法怎么办。请建议。谢谢。

【问题讨论】:

    标签: android http webview webviewclient


    【解决方案1】:

    方法onReceivedHttpError只支持API >= 23,你可以使用onReceivedError来支持API低于21和高于21。

        @TargetApi(Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
            onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
        }
    
        @SuppressWarnings("deprecation")
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            if (errorCode == -14) // -14 is error for file not found, like 404.
                view.loadUrl("http://youriphost");
        }
    

    更多详情https://developer.android.com/reference/android/webkit/WebViewClient.html#ERROR_FILE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 2017-06-18
      • 2014-11-19
      相关资源
      最近更新 更多