我在使用
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
PtrCLog.d("WebFragment", "onReceivedError: " + "");
}
這個方法並沒有被回掉查看了一下說是需要API23 才可以。 。有大佬知道有別的方法獲取404嗎?
滿天的星座2017-05-16 13:28:53
在onPageStarted裡邊跑一個AsyncTask,在AsyncTask裡用OkHttpClient之類的Http客戶端對需要存取的URL進行一次請求,取得code
class WebViewStatusRequester extends AsyncTask<String, String, Integer> {
@Override
protected void onPreExecute() {
super.onPreExecute();
web.setVisibility(View.GONE);
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if(result == 1) {
web.setVisibility(View.VISIBLE);
} else if(result == 0) {
showLoadFail();
}
}
@Override
protected 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;
}
}
在這裡實際上是Webview和OkHttpClient進行了加載,只是AsyncTask跑的時候把WebView隱藏起來了,確認是200了就顯示,不是200就顯示加載失敗的頁面