1、为什么要设置HTTP timeout?
1、与用户操作相关的接口,如果不设置超时时间,将会出现长时间的无响应,严重影响用户体验。
2、负载很高的系统,因为大量调用耗时长的接口,导致性能急剧下降,从而影响其他正常的业务。
3、某些情况下,HTTP请求可能永远都得不到响应,那么这部分系统资源就一直被占用,直到系统奔溃。
2、示例
public static void main(String[] args) throws Exception{
//创建httpclient
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建http get
HttpGet httpGet = new HttpGet("http://www.taotao.com/");
//构建超时等配置信息
RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) //连接超时时间
.setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
.setSocketTimeout(10 *1000) //数据传输的超时时间
.setStaleConnectionCheckEnabled(true) //提交请求前测试连接是否可用
.build();
//设置请求配置时间
httpGet.setConfig(config);
//接受返回的数据
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
}finally{
if(response!=null){
response.close();
}
httpClient.close();
}
3、Httpclient不同版本设置超时时间的方法是不一样的,要特别注意:
这是个3.X的超时设置方法
HttpClient client = new HttpClient();
client.setConnectionTimeout(30000);
client.setTimeout(30000);
4.3版本超时设置
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet=new HttpGet("http://www.baidu.com");//HTTP Get请求
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间
httpGet.setConfig(requestConfig);
httpClient.execute(httpGet);//执行请求