diff --git a/spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java b/spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java index 239ddf0a69f9..fc791caab737 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java +++ b/spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,6 +127,7 @@ public Mono write(Publisher inputStream, ResolvableType eleme return body .singleOrEmpty() .switchIfEmpty(Mono.defer(() -> { + message.getHeaders().setContentType(null); message.getHeaders().setContentLength(0); return message.setComplete().then(Mono.empty()); })) diff --git a/spring-web/src/test/java/org/springframework/http/codec/EncoderHttpMessageWriterTests.java b/spring-web/src/test/java/org/springframework/http/codec/EncoderHttpMessageWriterTests.java index eff738c3c9f0..58479195e16f 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/EncoderHttpMessageWriterTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/EncoderHttpMessageWriterTests.java @@ -33,7 +33,9 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import org.springframework.core.ResolvableType; import org.springframework.core.codec.CharSequenceEncoder; +import org.springframework.core.codec.Encoder; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.http.MediaType; @@ -199,6 +201,30 @@ void isStreamingMediaType() throws InvocationTargetException, IllegalAccessExcep assertThat((Boolean) method.invoke(writer, TEXT_HTML)).isFalse(); } + @Test + public void noContentTypeWithEmptyBody() { + Encoder encoder = CharSequenceEncoder.textPlainOnly(); + HttpMessageWriter writer = new EncoderHttpMessageWriter<>(encoder); + Mono writerMono = writer.write(Mono.empty(), ResolvableType.forClass(String.class), + null, this.response, NO_HINTS); + + StepVerifier.create(writerMono) + .verifyComplete(); + assertThat(response.getHeaders().getContentType()).isNull(); + } + + @Test + public void zeroContentLengthWithEmptyBody() { + Encoder encoder = CharSequenceEncoder.textPlainOnly(); + HttpMessageWriter writer = new EncoderHttpMessageWriter<>(encoder); + Mono writerMono = writer.write(Mono.empty(), ResolvableType.forClass(String.class), + null, this.response, NO_HINTS); + + StepVerifier.create(writerMono) + .verifyComplete(); + assertThat(this.response.getHeaders().getContentLength()).isEqualTo(0); + } + private void configureEncoder(MimeType... mimeTypes) { configureEncoder(Flux.empty(), mimeTypes); }