dsiori 2019-08-19 19:59 采纳率: 0%
浏览 1832
已结题

求解httpClient发送请求访问接口时,有时能连接,有时连接不上

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);
                }
            }
        }
    }

  • 写回答

3条回答 默认 最新

  • threenewbee 2019-08-20 00:32
    关注

    fiddler抓包看下,无非这么几个地方耗时,dns解析、网络,这个你可以优化,还有就是服务器性能问题,服务器故意限制。这个可以用抓包确认下,但是没法解决。

    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误