javaapache-httpclient-4.xcontent-length

Howto send PUT request without content and Content-Length header with Apache http client?


I'd like to test (via automated test) how server (and all proxies in-the-middle) responds to a PUT request without body and Content-Length header.

Similar to what curl does

curl -XPUT http://example.com

with Apache HTTP client (4.5.13)

But it looks like it always adds Content-Length header if I specify no body. Is there any way to do that with Apache HTTP client?

Already tried (no luck)

final HttpPut request = new HttpPut(url);
request.removeHeaders("Content-Length");

Solution

  • Use a request interceptor to modify requests generated by the standard protocol processor

    CloseableHttpClient httpClient = HttpClients.custom()
            .addInterceptorLast((HttpRequestInterceptor) (request, context) ->
                    request.removeHeaders(HttpHeaders.CONTENT_LENGTH))
            .build();
    HttpPut httpPut = new HttpPut("http://httpbin.org/put");
    httpClient.execute(httpPut, response -> {
        EntityUtils.consume(response.getEntity());
        return null;
    });