HttpClient升级到4.5版本后,API有不少变化,HttpClient 4以后,API一直没有太稳定,我感受4.5版本抽象后,不少API应该快稳定了。java
使用HttpClient,通常都须要设置链接超时时间和获取数据超时时间。这两个参数很重要,目的是为了防止访问其余http时,因为超时致使本身的应用受影响。ui
4.5版本中,这两个参数的设置都抽象到了RequestConfig中,由相应的Builder构建,具体的例子以下:spa
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://stackoverflow.com/"); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(1000) .setSocketTimeout(5000).build(); httpGet.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpGet); System.out.println("获得的结果:" + response.getStatusLine());//获得请求结果 HttpEntity entity = response.getEntity();//获得请求回来的数据
setConnectTimeout:设置链接超时时间,单位毫秒。code
setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,由于目前版本是能够共享链接池的。blog
setSocketTimeout:请求获取数据的超时时间,单位毫秒。 若是访问一个接口,多少时间内没法返回数据,就直接放弃这次调用。接口