android 下webview 如何判斷404?
問題描述
我在使用
@Overridepublic void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); PtrCLog.d('WebFragment', 'onReceivedError: ' + '');}
這個(gè)方法并沒有被回掉查看了一下說是需要API23 才可以。。有大佬知道有別的方法獲取404嗎?
問題解答
回答1:new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {super.onReceivedError(view, errorCode, description, failingUrl);if (errorCode == 404) { doSomething();} } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {super.onReceivedError(view, request, error);if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { int errorCode = error.getErrorCode(); if (errorCode == 404) {doSomething(); }} }};回答2:
在onPageStarted里邊跑一個(gè)AsyncTask,在AsyncTask里用OkHttpClient之類的Http客戶端對(duì)需要訪問的URL進(jìn)行一次請(qǐng)求,取得code
class WebViewStatusRequester extends AsyncTask<String, String, Integer> {@Overrideprotected void onPreExecute() { super.onPreExecute(); web.setVisibility(View.GONE);}@Overrideprotected void onPostExecute(Integer result) { super.onPostExecute(result); if(result == 1) {web.setVisibility(View.VISIBLE); } else if(result == 0) {showLoadFail(); }}@Overrideprotected Integer doInBackground(String... params) { String url = params[0]; if(url.substring(0, 4).equals('file') == false) {try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if(response.isSuccessful()) {return 1; } else {Log.i('TAG', 'fail code:' + response.code());return 0; }} catch (IOException e) { e.printStackTrace();}return 0; } return 1;} }
在這里實(shí)際上是Webview和OkHttpClient進(jìn)行了加載,只是AsyncTask跑的時(shí)候把WebView隱藏起來了,確認(rèn)是200了就顯示,不是200就顯示加載失敗的頁(yè)面
相關(guān)文章:
1. mysql - 表名稱前綴到底有啥用?2. 致命錯(cuò)誤: Class ’appfacadeTest’ not found3. 老師們php,插入數(shù)據(jù)庫(kù)mysql,都是空的,要怎么解決4. 求大神支招,php怎么操作在一個(gè)html文件的<head>標(biāo)記內(nèi)添加內(nèi)容?5. php點(diǎn)贊一天一次怎么實(shí)現(xiàn)6. 怎么php怎么通過數(shù)組顯示sql查詢結(jié)果呢,查詢結(jié)果有多條,如圖。7. PHP類屬性聲明?8. sql語(yǔ)句 - 如何在mysql中批量添加用戶?9. phpstady在win10上運(yùn)行10. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項(xiàng)
