Skip to content

Commit 7636eec

Browse files
kilinksbrannen
authored andcommitted
Use readNBytes in StringHttpMessageConverter when contentLength is available
When the content length is known, use readNBytes on the InputStream in StringHttpMessageConverter, which avoids some extra copying and allocations. Closes gh-30942
1 parent d890827 commit 7636eec

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

spring-web/src/main/java/org/springframework/http/converter/StringHttpMessageConverter.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,14 @@ public boolean supports(Class<?> clazz) {
9393
@Override
9494
protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException {
9595
Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
96-
return StreamUtils.copyToString(inputMessage.getBody(), charset);
96+
long length = inputMessage.getHeaders().getContentLength();
97+
final byte[] bytes;
98+
if (length >= 0 && length <= Integer.MAX_VALUE) {
99+
bytes = inputMessage.getBody().readNBytes((int) length);
100+
} else {
101+
bytes = inputMessage.getBody().readAllBytes();
102+
}
103+
return new String(bytes, charset);
97104
}
98105

99106
@Override

spring-web/src/test/java/org/springframework/http/converter/StringHttpMessageConverterTests.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,17 @@ public void read() throws IOException {
7070
assertThat(result).as("Invalid result").isEqualTo(body);
7171
}
7272

73+
@Test
74+
public void readWithContentLengthHeader() throws IOException {
75+
String body = "Hello World";
76+
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
77+
inputMessage.getHeaders().setContentLength(body.length());
78+
inputMessage.getHeaders().setContentType(TEXT_PLAIN_UTF_8);
79+
String result = this.converter.read(String.class, inputMessage);
80+
81+
assertThat(result).as("Invalid result").isEqualTo(body);
82+
}
83+
7384
@Test // gh-24123
7485
public void readJson() throws IOException {
7586
String body = "{\"result\":\"\u0414\u0410\"}";

0 commit comments

Comments
 (0)