Apache Http 客户端超时问题

Apache Http Client timout issue

我有这部分代码:

         RequestConfig requestConfig = RequestConfig.custom()
                        .setConnectTimeout(30 * 1000)
                        .setSocketTimeout(30 * 1000)
                        .setConnectionRequestTimeout(30 * 1000)
                        .build();

         BotSynch.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

         httpClient.execute(post);

BotSynch.HttpClient 是一个 class 字段

private static CloseableHttpClient httpClient;

最后一行的 post 是一个 HttpPost。

到目前为止,我的实现运行良好,但如果我连接的服务器在 30 秒内没有响应 post 请求,则什么也没有发生。

有时我可能需要长达 10 分钟才能收到服务器对请求的答复,这实际上是我试图通过上面的超时设置来阻止的。

我在这里遗漏了什么或者除了这个设置之外还应该处理什么吗?

如果预期的行为是 HttpClient#execute 调用永远不会超过 30 秒,无论执行结果如何,您应该考虑在后台线程方法中使用 HttpUriRequest#abort 方法,该方法可能在指定的时间间隔后中止请求。

    final HttpGet request = new HttpGet();
    ScheduledExecutorService executorService = ...
    executorService.schedule(request::abort, (long)30, TimeUnit.SECONDS);
    HttpResponse response = httpClient.execute(request);

我们(包括我自己)永远不应该忘记这不是 socketTimeout 所做的。