任何程序都需要处理异常,而使用外部服务(比如HTTP服务)的软件必须更加关注异常,因为出现错误的可能性更大。超时异常,应该是较为常见的一种。一种简单有效的处理方法就是,使用try/catch包装HTTP请求的execute()方法,然后出现在请求失败时重试.
public String executeHttpGet() throws Exception{
//使用Get方式访问网络,具体的方法可以参考我的文章http://blog.csdn.net/jiaoshi0531/archive/2011/05/30/6455765.aspx
}
public String executeHttpGetWithRetry(){
int retry = 3;
int count = 0;
while(count < retry){
count += 1;
try{
String response = executeHttpGet();
//如果成功,则停止循环
return response;
}catch(Exception e){
if(count < retry){
//继续重试
}else{
//重试3次后请求失败
}
}
}
}