Skip to content

Commit

Permalink
Merge pull request spring-projects#32622 from NadChel:bugfix/GH-32620…
Browse files Browse the repository at this point in the history
…_remove_content_type_if_no_body

* spring-projectsgh-32622:
  Polishing external contribution
  Remove Content-Type when body is empty
  • Loading branch information
poutsma committed Apr 23, 2024
2 parents adc7f73 + 6c5ef97 commit df41bb1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -127,6 +127,7 @@ public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType eleme
return body
.singleOrEmpty()
.switchIfEmpty(Mono.defer(() -> {
message.getHeaders().setContentType(null);
message.getHeaders().setContentLength(0);
return message.setComplete().then(Mono.empty());
}))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -199,6 +201,30 @@ void isStreamingMediaType() throws InvocationTargetException, IllegalAccessExcep
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);
}
Expand Down

0 comments on commit df41bb1

Please sign in to comment.