// 创建http请求客户端
DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 80000);
client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3,true));
socket read没有超时设置,会导致HttpClient阻塞,因为Http Client默认的SO_TIMEOUT是0,即一直等待。
Apache HttpClient需要设置TimeOut。两个timeout,一个是获取连接的timeout:CONNECTION_TIMEOUT,还有一个是socket的timeout,表示获取请求返回内容的超时时间SO_TIMEOUT。
setHttpRequestRetryHandler是设置请求的超时重试次数,超时了进行重试3次,true为重试开关。
上面讲的超时重试不好用,需要改成下面这种方法
public class Test {
public static void main(String[] args) throws Exception {
String url = "http://localhost/jiaowu/?dsdf=sdfd";
DefaultHttpClient client = new DefaultHttpClient();
org.apache.http.params.HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
HttpConnectionParams.setSoTimeout(params, 10 * 1000);
HttpGet request = new HttpGet(url);
sendRequest(client,request,3);
}
static void sendRequest(HttpClient client, HttpGet request, int count) {
for (int i = 0; i < count; i++) {
try {
System.out.println(new Date().toLocaleString());
client.execute(request);
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}