从老版本和新版本进行比较说明:

1.创建HttpClient对象

3.X:


HttpClient httpClient = new DefaultHttpClient();


4.3:


CloseableHttpClient httpClient = HttpClients.createDefault();


2.超时设置:

3.X:


HttpClient httpClient = new HttpClient();
client.setConnectionTimeout(30000);
client.setTimeout(30000);


或者:


HttpClient httpClient= new HttpClient(); 
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);


4.X(4.3后已过时):


HttpClient httpClient=new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//连接时间
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000); //数据传输时间


4.3:


CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost=new HttpPost("http://www.baidu.com"); //HTTP post请求
// 请求获取数据的超时时间 、 设置从connect Manager获取Connection超时时间、设置连接超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectionRequestTimeout(3000).setConnectTimeout(10000).build();
httpPost.setConfig(requestConfig);


3.httpclient 4.3.1,当不设置 超时时间的时候

  如果请求的url是通的,但服务器没有响应,会一直等待响应;

  如果请求的url是不通的,21秒后会报:Connection timed out: connect