Apache HttpClient:在收到400(错误请求)时带有安全重试的结果。

huangapple go评论62阅读模式
英文:

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

问题

以下是翻译好的内容:

我正在使用Apache的HttpClientFailsafe Java库。以下是伪代码的示例:

RetryPolicy<CloseableHttpResponse> policy = new RetryPolicy<>()
                .handleResultIf(/* 响应代码为404 */)
                .withMaxRetries(5)
                .withDelay(Duration.ofSeconds(10));

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

它在localhost上调用一个测试端点,并且我已经模拟它执行以下操作:

  • 前3个请求返回404
  • 第4个请求返回200

现在,当我执行上述代码时,我看到以下行为:

  1. HttpClient发送get请求,结果为404
  2. 由于响应是404,重试策略开始工作并重新尝试请求
  3. 重试的请求以400失败,未能实际到达代理
  4. 所有后续的重试都以400失败。响应没有任何主体

我期望步骤2中的请求能够命中我的模拟,然而它在未命中的情况下失败。HttpClient是否缓存响应或尝试阻止后续的重试?

英文:

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

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

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

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

  • Return 404 for the first 3 requests
  • Return 200 for the 4th request

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?

答案1

得分: 0

显然,在调用httpClientexecute方法之前,我是使用addHeader方法在请求中设置了头部。这导致请求中出现了重复的Content-TypeAuthorization头部。

由于这些头部值肯定是无效的,所以请求在未能命中URL之前就产生了400错误。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月20日 19:31:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64444251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定