在使用WebView中,我们不可避免的会接触到WebView加载失败的异常处理的需求,这时候,需要我们监听失败的方法也就是onReceivedError方法:
public class CustomWebViewClient extends WebViewClient { @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { int errorCode = error.getErrorCode(); String errorMessage = error.getDescription().toString(); Log.i("CustomWebViewClient", "onReceivedError errorCode : " + errorCode + " errorMessage : " + errorMessage); } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Log.i("CustomWebViewClient", "onReceivedError errorCode : " + errorCode + " description : " + description); } } }
注意: WebViewClient 的 onReceivedError()方法要根据安卓版本做版本兼容,android 6.0及以上回调上面的方法,如果是6.0以下,回调下面的函数。
下面是errorCode的列举:
public static final int ERROR_UNKNOWN = -1; public static final int ERROR_HOST_LOOKUP = -2; public static final int ERROR_UNSUPPORTED_AUTH_SCHEME = -3; public static final int ERROR_AUTHENTICATION = -4; public static final int ERROR_PROXY_AUTHENTICATION = -5; public static final int ERROR_CONNECT = -6; public static final int ERROR_IO = -7; public static final int ERROR_TIMEOUT = -8; public static final int ERROR_REDIRECT_LOOP = -9; public static final int ERROR_UNSUPPORTED_SCHEME = -10; public static final int ERROR_FAILED_SSL_HANDSHAKE = -11; public static final int ERROR_BAD_URL = -12; public static final int ERROR_FILE = -13; public static final int ERROR_FILE_NOT_FOUND = -14; public static final int ERROR_TOO_MANY_REQUESTS = -15;
来源地址:https://blog.csdn.net/Jason_HD/article/details/131440422