android 404页面,How can I check from Android WebView if a page is a "404 page not found"? - Stack Over...

该博客介绍了如何在Android的WebView中处理页面加载错误。通过监听`onReceivedTitle`事件,当页面标题包含特定的“页面未找到”文本时,停止加载当前页面,并重定向到Google搜索。同时,它还展示了如何使用`onProgressChanged`更新进度条,并在`onPageFinished`中关闭加载对话框。在遇到错误时,会显示一个Toast提示。

I might be a few years too late, but here is how I had to solve it since none of these answers worked.

I ended up using onReceivedTitle and comparing the title with the title of the page (in this case "page not found") from the site I was trying to open.

webview.setWebChromeClient(new WebChromeClient() {

@Override

public void onReceivedTitle(WebView view, String title) {

// TODO Auto-generated method stub

super.onReceivedTitle(view, title);

CharSequence pnotfound = "The page cannot be found";

if (title.contains(pnotfound)) {

pagenotfound = true;

view.stopLoading();

webview.loadUrl("https://www.google.com/search?hl=en&q=stackoverflow");

}

}

public void onProgressChanged(WebView view, int progress) {

activity.setProgress(progress * 1000);

}

});

webview.setWebViewClient(new WebViewClient() {

@Override

public void onReceivedError(WebView view, int errorCode,

String description, String failingUrl) {

Toast.makeText(activity, "Oh no! " + description,

Toast.LENGTH_SHORT).show();

}

public boolean shouldOverrideUrlLoading(WebView view, String url) {

view.loadUrl(url);

return true;

}

public void onPageFinished(WebView view, String url) {

if (dialog.isShowing()) {

dialog.dismiss();

}

}

});

The "pnotfound" will be different from site to site. But usually one site use the same "page not found" therefore you can use the Title on the site.

You might want to add a else if for if you're using multiple sites.

Hope it helps for someone.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值