RT:求解httpClient发送请求访问接口时,有时能连接,有时连接不上,连接上了以后,下一次查询很快,求大神帮忙查看,感谢。
问题:
1、使用的是 org.apache.http.impl.client.CloseableHttpClient;
2、访问接口时,有时能连接,有时连接不上
备注:
1、因为公司的策略情况,使用的是http1.0的中的短连接。使用抓包工具看,连接不上的时候一直是TCP重连,待超过设置的超时时间后查询不到数据。
2、网上查看了有说超时时间太长,设置短了更查不到数据
3、应用部署使用tomcat和docker都试过,效果一样。
4、接口是提供给多个系统使用,只有我调用存在此类问题。
5、使用postman调用速度比代码调用快。
抓包内容 :
httpClient代码
public static String postRequest(String url, String jsonString){
CloseableHttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60000)
.setConnectTimeout(60000)
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
//使用http1.0的短连接
httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
httpPost.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type", "application/json");
StringEntity requestEntity = new StringEntity(jsonString, "utf-8");
httpPost.setEntity(requestEntity);
try {
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8");
return resultStr;
} else {
return null;
}
} catch (Exception e) {
logger.error("httpPost method exception handle-- > " + e);
return null;
} finally {
if (httpResponse != null){
try {
httpResponse.close();
} catch (IOException e) {
logger.error("httpPost method IOException handle -- > " + e);
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
logger.error("httpPost method exception handle-- > " + e);
}
}
}
}