刚刚开始学习android开发,遇到一个场景,使用webview来嵌入wap页面,从而达到共享wap组件的效果。初试了下,发现webview无法截获404,500等错误,这个感觉很不方便,难道webview截获webkit的返回结果进行相应的操作这么复杂吗?不太理解webview为什么没有封装出更丰富的http response code的处理回调接口。然而如果用webview我想404等错误的处理是必不可少的,毕竟我们嵌入的是人家的网页,不能保证一定是正常的。想了下有2个办法可以做到对返回错误结果的捕获和处理:
1. 看源代码,分析webview封装webkit的原理,在学习一下webkit的错误处理机制,从而扩展webview增加回调处理404等错误的功能。
2. 在webview加载页面之前,使用httpclient的httphead来获取访问url的相应头,如果有错就不加载。
由于是新手,我想第一个办法肯定比较困那,就是熟手也不一定能在短时间内搞定,还是选择第2个办法。
简单的判断代码如下:
java代码
/**
* 检查url返回内容是否有效
* @param url
* @return
*/
private boolean validstatuscode(string url) {
if (this.mhttpclient == null) {
this.mhttpclient = httputils.createhttpclient();
}
try {
httphead httpget = new httphead(url);
httpresponse response = mhttpclient.execute(httpget);
int statuscode = response.getstatusline().getstatuscode();
string str = string.valueof(statuscode);
if (str.startswith("4") || str.startswith("5")) {
return false;
}
return true;
} catch (exception e) {
log.e(tag, e.getmessage(),e);
}
return false;
}
对于上面代码中的httputils.createhttpclient()方法,就不列出了,就是创建一个httpclient对象。
当然还有一点需要注意就是,通过httphead访问网络的时候,需要结合使用handler的机制来处理返回结果,以便在ui线程里面更新页面的显示。于是可以在一个新的线程里面来做网络的访问请求:
public class checkthread extends thread{
@override
public void run() {
boolean ifvalid = validstatuscode(reg_url);
message msg = new message();
bundle bundle = new bundle();
bundle.putboolean("validresponse", ifvalid);
msg.setdata(bundle);
mhandler.sendmessage(msg);
最后实现handler来处理httphead的请求结果来刷新ui展现:
private handler mhandler = new handler() {
public void handlemessage(message msg) {
bundle bundle = msg.getdata();
boolean validresponse = bundle.getboolean("validresponse");
if(validresponse) {
createwebview();
} else {
handlererror();
super.handlemessage(msg);
};