1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > httpclient: 设置请求的超时时间 连接超时时间等

httpclient: 设置请求的超时时间 连接超时时间等

时间:2018-06-26 19:36:15

相关推荐

httpclient: 设置请求的超时时间 连接超时时间等

1、为什么要设置HTTP timeout?

1、与用户操作相关的接口,如果不设置超时时间,将会出现长时间的无响应,严重影响用户体验。

2、负载很高的系统,因为大量调用耗时长的接口,导致性能急剧下降,从而影响其他正常的业务。

3、某些情况下,HTTP请求可能永远都得不到响应,那么这部分系统资源就一直被占用,直到系统奔溃。

2、示例

public static void main(String[] args) throws Exception{//创建httpclientCloseableHttpClient httpClient = HttpClients.createDefault();//创建http getHttpGet httpGet = new HttpGet("/");//构建超时等配置信息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 Get请求RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间httpGet.setConfig(requestConfig);httpClient.execute(httpGet);//执行请求

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。