duan5564712 2019-01-16 15:51 采纳率: 0%
浏览 472

http超时有些没有控制住

设置超时时间为3秒,大部分能控制住,但是还是有10秒或者10分钟以上的
麻烦大神帮忙看看,以下是使用的方法,

private static Logger logger = LoggerFactory.getLogger(SpringRestTemplateUtils.class);
    public static RestTemplate restTemplate;
    public static CloseableHttpClient client;
    public static HttpComponentsClientHttpRequestFactory factory;

    static{
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
         connMgr.setMaxTotal(2000);
         connMgr.setDefaultMaxPerRoute(500);
         client = HttpClients.custom()
              .setConnectionManager(connMgr)
              .build();
         factory = new HttpComponentsClientHttpRequestFactory(client);
         Thread thread = new Thread(new IdleConnectionMonitorThread(connMgr));
         thread.start();
    }

    /**
     * 
     * @param url 请求url
     * @param httpMethod 请求方式:HttpMethod.POST HttpMethod.GET
     * @param header 报文头设置
     * @param params JSON格式
     * @param readTimeOut 响应超时时间(单位:毫秒)
     * @param connectTimeOut 请求超时时间(单位:毫秒)
     * @return
     */
    public static String exchange(String url, HttpMethod httpMethod, HttpHeaders header, JSONObject params, int readTimeOut, int connectTimeOut){
        factory.setReadTimeout(readTimeOut);
        factory.setConnectTimeout(connectTimeOut);
        if(restTemplate == null){
              restTemplate = new RestTemplate(factory);
        }
        //MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8");
        //header.setContentType(type);
        HttpEntity<JSONObject> h = new HttpEntity<>(params, header);
        try {
             ResponseEntity<String> resp = restTemplate.exchange(url, httpMethod, h, String.class);
             return resp.getBody();
        }catch (HttpClientErrorException e) {
            return e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
           return e.getResponseBodyAsString();
        } catch (Exception e) {
            logger.error("#########远程请求原始异常",e);
            if(e.getCause() == null || (!(e.getCause() instanceof SocketTimeoutException) && !(e.getCause() instanceof ConnectTimeoutException))){
                restTemplate = null;
            }else{
                throw e;
            }
            return null;
        }
    }
  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-21 01:55
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!