Skip to content

Set Content-Length Header in EncoderHttpMessageWriter Only for GET Requests if Value is Greater than 0 #35999

@PawelTo

Description

@PawelTo

When using Spring Cloud Gateway with custom request decorators that cache request bodies, the ‎EncoderHttpMessageWriter::write class (invoked by BodyInserters.insert() automatically calculates and sets the Content-Length header based on the buffered body content, even when the original request intentionally did not include this header.

The EncoderHttpMessageWriter always sets Content-Length for the upstream request, regardless of whether:

  • The original client request had Content-Length
  • The body is empty (length = 0)
  • The request method is GET

Environment:
Spring Cloud Gateway version: 2023.0.3
Spring Boot version: 3.2.11
Java version: 17

Suggested fix:
Update the logic in EncoderHttpMessageWriter to check byte count.

return body
        .singleOrEmpty()
        .switchIfEmpty(
            Mono.defer(() -> {
                message.getHeaders().setContentLength(0);
                return message.setComplete().then(Mono.empty());
            })
        )
        .flatMap(buffer -> {
            Hints.touchDataBuffer(buffer, hints, logger);
            int contentLength = buffer.readableByteCount();
            if (contentLength > 0) {
                message.getHeaders().setContentLength(contentLength);
            }
            return message.writeWith(
                Mono.just(buffer)
                    .doOnDiscard(DataBuffer.class, DataBufferUtils::release)
            );
        })
        .doOnDiscard(DataBuffer.class, DataBufferUtils::release);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions