网上大部分找到的是overstack如下方法,自己模拟一个httpClient
对httpget惊醒请求,经测试,不可用,不能拦截500的错误。stat = one 就打印不出。
@Override
public boolean shouldOverrideUrlLoading(WebView view, String
urlConection) {
ToastUtil.popupToast(getApplicationContext(), "stat =
one");
URL url;
URLConnection conexion;
try {
url = new URL(urlConection);
conexion = url.openConnection();
conexion.setConnectTimeout(3000);
conexion.connect();
// get the size of the file which is in the header of
the
// request
int size = conexion.getContentLength();
} catch (Exception e) {
e.printStackTrace();
ToastUtil.popupToast(getApplicationContext(), "stat =
two");
}
// and here, if you want, you can load the page normally
String htmlContent = "";
HttpGet httpGet = new HttpGet(urlConection);
// this receives the response
HttpResponse response;
ToastUtil.popupToast(getApplicationContext(), "stat =
start");
try {
HttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(httpGet);
ToastUtil.popupToast(getApplicationContext(), "stat = " +
response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
// la conexion fue establecida, obtener el contenido
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
htmlContent = convertToString(inputStream);
}
} else {
// 返回码 非200,均提示小哭脸
pageLoadSuccess = false;
}
ToastUtil.popupToast(getApplicationContext(), "stat = " +
response.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
view.loadData(htmlContent, "text/html", "utf-8");
return true;
}
public String convertToString(InputStream inputStream) {
StringBuffer string = new StringBuffer();
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
String line;
try {
while ((line = reader.readLine()) != null) {
string.append(line + "\n");
}
} catch (IOException e) {
}
return string.toString();
}
---------------------------------------------------------
目前我能解决的就是处理404等一些浏览器器解析的错误,像类似500这种服务端的响应
,实际上已经是httpget正确,但是服务server方解析或者处理异常(空指针等情况),目前还没找到webview
对这方面的回调相应。
对应由浏览器相应的解决想法如下,这也是自己琢磨出来的,他会自己去起一个Android
assert下的默认错误页面。
@Override
public void onLoadResource(WebView view, String url) {
if (url != null &&
url.equals("file:///android_asset/webkit/android-weberror.png"))
{
ll_no_data.setVisibility(View.VISIBLE);
pageLoadSuccess = false;
} else {
ll_no_data.setVisibility(View.GONE);
}
}