HTTP状态代码webview android、WebViewClient

HTTP状态代码webview android、WebViewClient,android,http,webview,webviewclient,Android,Http,Webview,Webviewclient,所以我读了很多关于某某的问题,仍然想问这个。我的片段中有一个webview。我正在调用一个url,想知道HTTP状态码(成功或失败)。我已经从WebViewClient类扩展了一个类,下面是相同的片段 我遇到了这种方法: @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.

所以我读了很多关于某某的问题,仍然想问这个。我的片段中有一个webview。我正在调用一个url,想知道HTTP状态码(成功或失败)。我已经从WebViewClient类扩展了一个类,下面是相同的片段

我遇到了这种方法:

@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。我把这当作变通办法。但是,如果我想避免使用这种不推荐的方法呢。请建议。谢谢。

方法OnReceivedHttPeror仅支持API>=23,您可以使用onReceivedError支持低于21和高于21的API

    @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");
    }
更多细节