HttpClient 5.0 设置超时时间需要使用RequestConfig类,具体方法如下:
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000, TimeUnit.MILLISECONDS).setConnectTimeout(10000, TimeUnit.MILLISECONDS).setResponseTimeout(10000, TimeUnit.MILLISECONDS).build();
相对于HttpClient 4.X版本,setConnectionTimeout方法需要多传一个参数:TimeUnit(时间单位);
TimeUnit的值有:
注意:HttpClient 5.0 版本没有setSocketTimeout方法(获取数据的超时时间);
如不设置超时时间,默认时间是3分钟
具体使用步骤:
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000, TimeUnit.MILLISECONDS).setConnectTimeout(10000, TimeUnit.MILLISECONDS).setResponseTimeout(10000, TimeUnit.MILLISECONDS).build();
//HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
CloseableHttpClient closeableHttpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
或者:
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000, TimeUnit.MILLISECONDS).setConnectTimeout(10000, TimeUnit.MILLISECONDS).setResponseTimeout(10000, TimeUnit.MILLISECONDS).build();
HttpPost httpost = new HttpPost(url);
httpost.setConfig(requestConfig);
新手程序员一枚,如有写错,望各位指正~