Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use readNBytes in StringHttpMessageConverter when contentLength is available #30942

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -93,7 +93,14 @@ public boolean supports(Class<?> clazz) {
@Override
protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException {
Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
return StreamUtils.copyToString(inputMessage.getBody(), charset);
long length = inputMessage.getHeaders().getContentLength();
final byte[] bytes;
if (length >= 0 && length <= Integer.MAX_VALUE) {
bytes = inputMessage.getBody().readNBytes((int) length);
} else {
bytes = inputMessage.getBody().readAllBytes();
}
return new String(bytes, charset);
}

@Override
Expand Down
Expand Up @@ -70,6 +70,17 @@ public void read() throws IOException {
assertThat(result).as("Invalid result").isEqualTo(body);
}

@Test
public void readWithContentLengthHeader() throws IOException {
String body = "Hello World";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
inputMessage.getHeaders().setContentLength(body.length());
inputMessage.getHeaders().setContentType(TEXT_PLAIN_UTF_8);
String result = this.converter.read(String.class, inputMessage);

assertThat(result).as("Invalid result").isEqualTo(body);
}

@Test // gh-24123
public void readJson() throws IOException {
String body = "{\"result\":\"\u0414\u0410\"}";
Expand Down