javaapache-httpclient-4.xretrypolicyjava-failsafe

Apache HttpClient : Retry with failsafe results in 400 (bad request)


I am using Apache HttpClient with Failsafe java library. Below is how the (pseudo) code looks like:

RetryPolicy<CloseableHttpResponse> policy = new RetryPolicy<>()
                .handleResultIf(/* Response code is 404 */)
                .withMaxRetries(5)
                .withDelay(Duration.ofSeconds(10));

CloseableHttpResponse response = Failsafe.with(policy).get(() -> httpClient.execute(myRequest));

It's calling a test endpoint at localhost and I have mocked it to do the following:

Now, when I execute the above code, I see the following behavior:

  1. HttpClient sends get request, it results in 404
  2. As the response is 404, retry policy kicks in and retries the request
  3. Retried request fails with 400 without actually reaching the proxy
  4. All the subsequent retries fail with 400. The response doesn't have any body

I expect the request in step 2 to hit my mock, however, it fails without hitting it. Does HttpClient cache the response or tries to prevent the subsequent retries?


Solution

  • Apparently, I was setting headers in the request with addHeader method before calling execute for httpClient. This resulted in requests with duplicate Content-Type and Authorization headers.

    As these header values are certainly invalid, the requests resulted in 400 error without hitting the url.