使用HttpClient可配置三种超时时间:RequestTimeOut(获取链接超时时间) 、connectTimeOut(建立链接超时时间)、SocketTimeOut(获取数据超时时间)。配置这三种超时时间,需要用到HttpClient的RequestConfig类中的custom()方法,该方法返回值为实例化内部类的Builder(配置器)。程序3-18是HttpClient进行超时设置的代码案例。

//程序3-18
public class HttpClientTimeout {
public static void main(String[] args) throws Exception {
//初始化httpClient
HttpClient httpClient = HttpClients.createDefault();
//Get请求(Post方法相似)
HttpGet httpGet=new HttpGet("https://searchcustomerexperience.techtarget.com/info/news");
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2*1000).setConnectTimeout(2*1000).setConnectionRequestTimeout(10*1000).build();
//httpGet信息配置
httpGet.setConfig(requestConfig);
HttpResponse response = null;
try {
//执行请求
response = httpClient.execute(httpGet);
}catch (Exception e){
e.printStackTrace();
}
//获取结果
String result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
}
}