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

求解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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀