webview onReceivedError 接收不到404

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

[code]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方法

[code]@Overridepublic 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,如果需要继续使用 在改方法上面加入

[code]@SuppressWarnings("deprecation")@Overridepublic void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {    // Handle the error}@TargetApi(android.os.Build.VERSION_CODES.M)@Overridepublic 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系统刚出来不久,市面上也还没有普及,能用老方法解决最好。在这里先表示感谢了。

转自:http://www.th7.cn/Program/Android/201512/736148.shtml

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值