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

求解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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题