HTTP状态码webview android, WebViewClient

Posted

技术标签:

【中文标题】HTTP状态码webview android, WebViewClient【英文标题】:HTTP status code 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。我将此作为解决方法。但是,如果我想避免使用这种已弃用的方法怎么办。请建议。谢谢。

【问题讨论】:

【参考方案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

【讨论】:

以上是关于HTTP状态码webview android, WebViewClient的主要内容,如果未能解决你的问题,请参考以下文章

UIWebView 从加载的页面获取 http 状态码

android中webview 怎么实现网页加载时显示加载进度

Android:WebView loadDataWithBaseURL 不显示验证码图片

Android(H5)互相调用方法

将Playbuzz加载脚本加载到Android中的WebView中

在android webview上暂停/恢复svg动画