保捱科技网
您的当前位置:首页HttpClient如何设置超时时间

HttpClient如何设置超时时间

来源:保捱科技网
HttpClient如何设置超时时间

今天分享⼀个巨坑,就是 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\ 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的那种⽅式,解决问题。

因篇幅问题不能全部显示,请点此查看更多更全内容