HttpClient  4.5版本设置连接超时时间-CloseableHttpClient设置Timeout(区别于4.3.2)

HttpClient升级到4.5版本后,API有很多变化,HttpClient 4之后,API一直没有太稳定,我感觉4.5版本抽象后,很多API应该快稳定了。

使用HttpClient,一般都需要设置连接超时时间和获取数据超时时间。这两个参数很重要,目的是为了防止访问其他http时,由于超时导致自己的应用受影响。

4.5版本中,这两个参数的设置都抽象到了RequestConfig中,由相应的Builder构建,具体的例子如下:

  1. <code class="hljs go" style="font-family:'Courier New',Courier,monospace; font-size:1em">CloseableHttpClient httpclient = HttpClients.createDefault();
  2. HttpGet httpGet = new HttpGet("http://stackoverflow.com/");
  3. RequestConfig requestConfig = RequestConfig.custom()
  4. .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
  5. .setSocketTimeout(5000).build();
  6. httpGet.setConfig(requestConfig);
  7. CloseableHttpResponse response = httpclient.execute(httpGet);
  8. System.out.println("得到的结果:" + response.getStatusLine());//得到请求结果
  9. HttpEntity entity = response.getEntity();//得到请求回来的数据</code>

setConnectTimeout:设置连接超时时间,单位毫秒。

setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。

setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。

===========================================

昨天遇到一个问题需要设置CloseableHttpClient的超时时间,查了官方文档如下。

新建一个RequestConfig:

RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setStaleConnectionCheckEnabled(true)
.build();

这个超时可以设置为客户端级别,作为所有请求的默认值:

CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig)
.build();

Request不会继承客户端级别的请求配置,所以在自定义Request的时候,需要将客户端的默认配置拷贝过去:

 
HttpGet httpget = new HttpGet("http://www.apache.org/");
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
.setProxy(new HttpHost("myotherproxy", 8080))
.build();
httpget.setConfig(requestConfig);

伦理片 http://www.dotdy.com/  

4.3版本的超时是这样的:

public static String httpPost(String url, String jsonString) {
// 设置HTTP请求参数
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);//设置请求超时时间 10s
StringEntity entity = new StringEntity(jsonString);
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpEntity resEntity = httpClient.execute(httpPost).getEntity();
result = EntityUtils.toString(resEntity, "UTF-8");
} catch (Exception e) {
logger.error("http接口调用异常:url is::" + url, e);
return null;
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}

4.5.2版本是这样的:

public static String testTimeout(String url) {

// 设置HTTP请求参数

String result = null;

CloseableHttpClient client = HttpClients.createDefault();

HttpGet httpGet = new HttpGet(url);

RequestConfig requestConfig = RequestConfig.custom()

.setConnectTimeout(50000).setConnectionRequestTimeout(10000)

.setSocketTimeout(50000).build();

httpGet.setConfig(requestConfig);

try {

CloseableHttpResponse response = client.execute(httpGet);

result = EntityUtils.toString(response.getEntity(), "UTF-8");

} catch (ClientProtocolException e) {

logger.error("http接口调用异常:url is::" + url, e);

return null;

} catch (Exception e) {

logger.error("http接口调用异常:url is::" + url, e);

return null;

} finally {

try {

client.close();

} catch (IOException e) {

logger.error("http接口调用异常:url is::" + url, e);

}

}

return result;

}

转自:http://blog.csdn.net/h254532699/article/details/54342470

HttpClient设置超时(转)的更多相关文章

  1. android httpclient 设置超时

    3.X是这样的 HttpClient httpClient=new DefaultHttpClient();4.3是这样的CloseableHttpClient httpClient = HttpCl ...

  2. HttpClient设置代理,超时,以及得到cookies

    import java.net.URI; import java.util.List; import org.apache.http.HttpEntity; import org.apache.htt ...

  3. 转 HttpClient 设置连接超时时间

    要: HttpClient 4.5版本升级后,设置超时时间的API又有新的变化,请大家关注. HttpClient升级到4.5版本后,API有很多变化,HttpClient 4之后,API一直没有太稳 ...

  4. HttpClient库设置超时

    HttpClient库API跟Lucene一样,每个版本的API都变化很大,这有点让人头疼.就好比创建一个HttpClient对象吧,每一个版本的都不一样. 3.X是正常的Java语法 HttpCli ...

  5. httpClient创建对象、设置超时

    从老版本和新版本进行比较说明: 1.创建HttpClient对象 3.X: HttpClient httpClient = new DefaultHttpClient(); 4.3: Closeabl ...

  6. HttpClient 如何设置超时时间

    今天分享一个巨坑,就是 HttpClient.这玩意有多坑呢?就是每个版本都变,近日笔者深受其害. 先看一下代码,我要发送请求调用一个c++接口. public static String doPos ...

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

    httpclient: 设置请求的超时时间,连接超时时间等 public static void main(String[] args) throws Exception{ //创建httpclien ...

  8. [转]HttpClient的超时用法小记

    HttpClient的超时用法小记 HttpClient在使用中有两个超时时间,是一直接触和使用的,由于上次工作中使用httpClient造成了系统悲剧的情况,特地对它的两个超时时间进行了小小的测试, ...

  9. (五)HttpClient 连接超时及读取超时

    第一节: HttpClient 连接超时及读取超时 HttpClient连接超时及读取超时 httpClient在执行具体http请求时候 有一个连接的时间和读取内容的时间: HttpClient连接 ...

随机推荐

  1. Codechef APRIL14 ANUCBC Cards, bags and coins 背包DP变形

    题目大意 有n个数字,选出一个子集,有q个询问,求子集和模m等于0的方案数%1000000009.(n <= 100000,m <= 100,q <= 30) 假设数据很小,我们完全 ...

  2. Djangio笔记

    django图解 新创建一个项目后的目录层级

  3. Codeforces Round #299 (Div. 1) A. Tavas and Karafs 水题

    Tavas and Karafs Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/536/prob ...

  4. Redmine 邮件配置

    高版本号的Redmine是没有email.yml的.是和configuration.yml合并了.仅仅要配置configuration.yml即可了. 首先得说下Redmine的邮件,配置这个邮件,是 ...

  5. NativeXml: A native Delphi XML parser and writer

    http://www.simdesign.nl/xml.html This software component contains a small-footprint Object Pascal (D ...

  6. Linux操作系统的种种集成开发环境

    Linux操作系统的种种集成开发环境 随着Linux的逐渐兴起,已经有为数众多的程序在上面驰骋了,许多开发环境(Development Environment)也应运而生.好的开发环境一定是集成了编辑 ...

  7. 一个 MVC 框架以 MVVM 之「魂」复活了!

    GitHub: https://github.com/houfeng/mokit Mokit 最初编写于 2012 年,是一个面向移动应用的前端 mvc 框架,v3 版本进行了大量的重构或重写,并尽可 ...

  8. JAVA常见算法题(三十一)---冒泡排序

    package com.jege.spring.boot.hello.world; /** * java算法之冒泡排序<br> * 将数组按照从大到小的顺序排列<br> * * ...

  9. OpenShift跨版本升级

    官方的in-place upgrade直接在线升级的参考链接 https://docs.openshift.com/container-platform/3.11/upgrading/automate ...

  10. c++ 哈希表(hash表)

    一.定义 Hash表,也称散列表.一般应用于有大量"动态"的插入(删除)和查找操作的一类问题.(如果是"静态"的,通常可以先对数据排序,查找时就可以用" ...