Merge pull request #32622 from NadChel:bugfix/GH-32620_remove_content_type_if_no_body

* gh-32622:
  Polishing external contribution
  Remove Content-Type when body is empty
This commit is contained in:
Arjen Poutsma
2024-04-23 15:04:53 +02:00
2 changed files with 28 additions and 1 deletions

View File

@@ -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 class EncoderHttpMessageWriter<T> implements HttpMessageWriter<T> {
return body
.singleOrEmpty()
.switchIfEmpty(Mono.defer(() -> {
message.getHeaders().setContentType(null);
message.getHeaders().setContentLength(0);
return message.setComplete().then(Mono.empty());
}))

View File

@@ -33,7 +33,9 @@ import reactor.core.publisher.Flux;
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 @@ class EncoderHttpMessageWriterTests {
assertThat((Boolean) method.invoke(writer, TEXT_HTML)).isFalse();
}
@Test
public void noContentTypeWithEmptyBody() {
Encoder<CharSequence> encoder = CharSequenceEncoder.textPlainOnly();
HttpMessageWriter<CharSequence> writer = new EncoderHttpMessageWriter<>(encoder);
Mono<Void> 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<CharSequence> encoder = CharSequenceEncoder.textPlainOnly();
HttpMessageWriter<CharSequence> writer = new EncoderHttpMessageWriter<>(encoder);
Mono<Void> 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);
}