diff --git a/spring-web/src/main/java/org/springframework/http/converter/ByteArrayHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/ByteArrayHttpMessageConverter.java index 3a7025acbf12..31de40f3a9b4 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/ByteArrayHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/ByteArrayHttpMessageConverter.java @@ -52,7 +52,15 @@ public boolean supports(Class clazz) { @Override public byte[] readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException { - return inputMessage.getBody().readAllBytes(); + long contentLength = inputMessage.getHeaders().getContentLength(); + final int len; + if (contentLength >= 0 && contentLength <= Integer.MAX_VALUE) { + len = (int) contentLength; + } + else { + len = Integer.MAX_VALUE; + } + return inputMessage.getBody().readNBytes(len); } @Override diff --git a/spring-web/src/test/java/org/springframework/http/converter/ByteArrayHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/ByteArrayHttpMessageConverterTests.java index 612ec0ce4cde..5a00d76582f9 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/ByteArrayHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/ByteArrayHttpMessageConverterTests.java @@ -57,6 +57,16 @@ public void read() throws IOException { assertThat(result).as("Invalid result").isEqualTo(body); } + @Test + public void readWithContentLengthHeaderSet() throws IOException { + byte[] body = new byte[]{0x1, 0x2, 0x3, 0x4, 0x5}; + MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); + inputMessage.getHeaders().setContentType(new MediaType("application", "octet-stream")); + inputMessage.getHeaders().setContentLength(body.length); + byte[] result = converter.read(byte[].class, inputMessage); + assertThat(result).as("Invalid result").isEqualTo(body); + } + @Test public void write() throws IOException { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();