webview加载报错

最近有个同事问我,他的页面有一个请求失败了,然后整个H5就没办法加载了。分享一段代码,做个记录吧。

可以这样处理

priavte final class TestWebviewClient extends WebviewClient{

    @Override
    public boolean shouldOverrideUrlLoading(WebView webview, String url) {
        Lg.i(TAG, "shouldOverrideUrlLoading", url);
        boolean isValidUrl = !TextUtils.isEmpty(url) && (url.startsWith("https://") || url.startsWith("http://"));
        if (isValidUrl) mLastUrl = url;
        if (!isValidUrl) Lg.v(TAG, "invalid url,skipping", url);
        return !isValidUrl;// for not isValidUrl,return true to avoid loading
    }

    @Override
    public final void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        handleReceivedError(view, errorCode, description, failingUrl);
    }

    @Override
    public final void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        String failingUrl = null;
        int errorCode = -1;
        String description = "";
        if (VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            failingUrl = request.getUrl().toString();
        }
        if (VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            errorCode = error.getErrorCode();
            description = String.valueOf(error.getDescription());
        }
        handleReceivedError(view, errorCode, description, failingUrl);
    }

    private void handleReceivedError(WebView view, int code, String message, String url) {
        Lg.e(TAG, "onReceivedError", url, code, message);
        if (!TextUtils.isEmpty(url)) {
            url = url.replace("/?", "?");
            if (mLastUrl.equals(url)) {
                // only show reloading page when the main url receive error
                // (let it go when received other url's error)
                mHasError = true;
                updateLoadingStatus(ERROR);
            }
        }
    }
}
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页