Improve default content type handling

We now also check the default content type if the content type is
application/octet-stream as we do today.

Uncommented failing test that now passes.
This commit is contained in:
Rossen Stoyanchev 2016-06-24 18:14:11 -04:00
parent 351e834716
commit 0ff7df8b5c
3 changed files with 12 additions and 7 deletions

View File

@ -132,14 +132,22 @@ public class CodecHttpMessageConverter<T> implements HttpMessageConverter<T> {
if (this.encoder == null) {
return Mono.error(new IllegalStateException("No decoder set"));
}
HttpHeaders headers = outputMessage.getHeaders();
if (headers.getContentType() == null) {
MediaType contentTypeToUse = contentType;
if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
contentTypeToUse = getDefaultContentType(type);
}
headers.setContentType(contentTypeToUse);
else if (MediaType.APPLICATION_OCTET_STREAM.equals(contentType)) {
MediaType mediaType = getDefaultContentType(type);
contentTypeToUse = (mediaType != null ? mediaType : contentTypeToUse);
}
if (contentTypeToUse != null) {
headers.setContentType(contentTypeToUse);
}
}
DataBufferFactory bufferFactory = outputMessage.bufferFactory();
Flux<DataBuffer> body = this.encoder.encode(inputStream, bufferFactory, type, contentType);
return outputMessage.writeWith(body);

View File

@ -48,6 +48,7 @@ import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.core.convert.support.ReactiveStreamsToCompletableFutureConverter;
import org.springframework.core.convert.support.ReactiveStreamsToRxJava1Converter;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import org.springframework.http.HttpMethod;
@ -90,16 +91,12 @@ public class MessageConverterResultHandlerTests {
@Test // SPR-12894
@Ignore // GH # 121
public void useDefaultContentType() throws Exception {
Object body = new ByteArrayResource("body".getBytes("UTF-8"));
Resource body = new ClassPathResource("logo.png", getClass());
ResolvableType bodyType = ResolvableType.forType(Resource.class);
this.resultHandler.writeBody(this.exchange, body, bodyType).block(Duration.ofSeconds(5));
assertEquals("image/jpeg", this.response.getHeaders().getFirst("Content-Type"));
TestSubscriber.subscribe(this.response.getBody())
.assertValuesWith(buf -> assertEquals("body",
DataBufferTestUtils.dumpString(buf, Charset.forName("UTF-8"))));
assertEquals("image/x-png", this.response.getHeaders().getFirst("Content-Type"));
}
@Test

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB