HttpClient 如何设置超时时间

时间:2024-07-01 16:03:14

今天分享一个巨坑,就是 HttpClient。这玩意有多坑呢?就是每个版本都变,近日笔者深受其害。

先看一下代码,我要发送请求调用一个c++接口。

public static String doPostWithJSON(String url, String json) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
StringEntity se = new StringEntity(json, Charset.forName("UTF-8"));
se.setContentType("application/json");
httpPost.setEntity(se);
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
return result;
}

嗯,坑爹的地方来了,这个玩意发送请求,没设置超时时间,只要不响应,他能一直在这等着,这谁能受得了。

我要加个超时时间。

第二个大坑来了。

我记得以前设置超时时间是这样的。

client.setConnectionTimeout(10000); 
client.setTimeout(10000);

我发现,特么没这个方法。

于是查阅资料。发现HttpClient太善变了。每个版本都变api。

4.3版本是这样的

httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000);

4.3以后是这样的。

RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
httpGet.setConfig(requestConfig);

最后我根据我的版本,选了4.3的那种方式,解决问题。