spring-framework: BufferingClientHttpRequestFactory should not set content length for empty request body

We were recently moving from WebClient to RestClient and one of the 3rd parties we deal with started returning us: HTTP Error 411. The request must be chunked or have a content length

The given request is a POST without any body and looking at the outgoing requests the only difference between before and after is that now the request we generate has a Content-Length: 0 while before that header was absent.

I do concede that I’m not sure that the 3rd party is handling this properly, but I also have to say that I don’t see why the framework would be setting Content-Length: 0 when there is no body.

I was looking deeper into the code and I can see that the decision to add the Content-Length header is being taken here and that happens because headers.getContentLength() returns -1. Looking further at the logic on HttpHeaders I can see here that when that header is not set it just returns -1, which is happening in my case.

In my view I don’t think it makes sense to send this header in this case, so I was wondering if that could be fixed, perhaps by just doing instead:

if (bytes.length > 0 && headers.getContentLength() < 0) {
	headers.setContentLength(bytes.length);
}

This should still ensure that the header is added if it is missing and there is a body, but will not add it if there is no body. It will also not override if explicitly set.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 1
  • Comments: 19 (10 by maintainers)

Commits related to this issue

Most upvoted comments

@nhmarujo it’s fixed now in 6.1.7-SNAPSHOTs and it will be released with next month’s maintenance release. Thanks for your report!