Anna Klein
Anna Klein

Reputation: 2171

Apache Http Client timout issue

I have this part of code:

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

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

         httpClient.execute(post);

the BotSynch.HttpClient is a class field

private static CloseableHttpClient httpClient;

The post in the last line is a HttpPost.

My implementation so far works well, but if the Server I am connected to, doesn't answer to a post request in 30 seconds nothing is happening.

Sometimes it can take up to 10 minutes until I receive the answer from the server to the request and that is actually what I tried to prevent with the timeout setting above.

Is there something I missed here or something that should be handled beside this settings?

Upvotes: 0

Views: 326

Answers (1)

Ioannis Sermetziadis
Ioannis Sermetziadis

Reputation: 797

If the expected behavior is that the HttpClient#execute call should never take longer than 30 seconds, regardless of the execution result, you should consider using the HttpUriRequest#abort method in a background thread method that could abort the request after the specified interval.

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

We (myself included) should never forget that this is not what the socketTimeout does.

Upvotes: 1

Related Questions