您的位置:首页 > 移动开发

webview onReceivedError 接收不到404

2015-12-19 12:08 429 查看
在android里面加入webview的时候,有时候需要捕获http error,例如404等错误。在api 22 以下 系统提供onReceivedError方法。根据google官网提供的文档,onReceivedError可以捕获http Error。但是使用这个方法的时候,并没有捕获到404错误。

WebView webView = new WebView(this);
webView.setWebViewClient(new WebViewClient(){
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
webView.loadUrl("你加载的网址");


仔细查下了一下最新文档,原来google以前的文档存在bug,这里是google开发人员说的

**The docs are wrong in this case. We’ll update the docs to say that the errors are not HTTP errors but are

unrecoverable resource errors (file not found, no network connection, server not found for the main resource,

etc.).**

onReceivedError方法捕获的是 文件找不到,网络连不上,服务器找不到等问题,并不能捕获 http errors。

需要在webview里面捕获404 怎么办了?

google最新更新了文档,可以在api 23 也就是最新的6.0系统,可以捕获

重载onReceivedHttpError方法

@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
}


这里是这个bug的google issue链接

https://code.google.com/p/android/issues/detail?id=968

另外在sdk 23里面 onReceivedError(WebView view, int errorCode, String description, String failingUrl) 在 api 23里面 已经 deprecation,如果需要继续使用 在改方法上面加入

@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Handle the error
}

@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}


可以参考链接

http://stackoverflow.com/questions/32769505/webviewclient-onreceivederror-deprecated-new-version-does-not-detect-all-errors/32813234#32813234

网上有很多朋友说直接在onReceivedError方法里面可以直接捕获到404,但是我试了一下,依然是不行。如果有朋友试了可行的话,希望能贴出你的代码,分享一下。毕竟6.0系统刚出来不久,市面上也还没有普及,能用老方法解决最好。在这里先表示感谢了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息