webView加载一个404的路径时,会出现not found这样的内容显示出来,但是有时候我们需要在出现这样问题后,做其他处理,所有我们要捕获他的错误,但是SDK的错误处理方法居然不会在加载错误以后回调:
public voidonReceivedError (WebView view, int errorCode, String description, String failingUrl)
Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). The errorCode parameter corresponds to one of the ERROR_* constants.
Parameters
view
The WebView that is initiating the callback.
errorCode
The error code corresponding to an ERROR_* value.
description
A String describing the error.
failingUrl
The url that failed to load.
没办法,我们要习惯容忍SDK这些问题,下面说一个解决方式,那就是在加载的时候 做一个处理,重新连接一下这个URL,看看返回的code是什么,然后做处理,如下
private void checkWebViewUrl(final WebView webView, final String url) {
if (url==null||url.equals("")) {
return;
}
new AsyncTask() {
@Override
protected Integer doInBackground(String... params) {
int responseCode = -1;
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
responseCode = connection.getResponseCode();
} catch (Exception e) {
log.e("Loading webView error:" + e.getMessage());
}
return responseCode;
}
@Override
protected void onPostExecute(Integer result) {
if (result != 200) {
webView.setVisibility(View.GONE);
} else {
webView.loadUrl(url);
}
}
}.execute(url);
}
补充一点:最新发现只有设备的网络状态处于断开的情况下才会进入onReceivedError方法,如果是URL路径对应的服务端返回了404是不会进入这个方法的。