Skip to content

Commit 9464e4f

Browse files
author
liwenlong
committed
Avoid creating byte[] multiple times
1 parent 4bfc129 commit 9464e4f

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

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

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -99,13 +99,6 @@ protected String readInternal(Class<? extends String> clazz, HttpInputMessage in
9999
return new String(bytes, charset);
100100
}
101101

102-
@Override
103-
protected Long getContentLength(String str, @Nullable MediaType contentType) {
104-
Charset charset = getContentTypeCharset(contentType);
105-
return (long) str.getBytes(charset).length;
106-
}
107-
108-
109102
@Override
110103
protected void addDefaultHeaders(HttpHeaders headers, String s, @Nullable MediaType type) throws IOException {
111104
if (headers.getContentType() == null ) {
@@ -125,7 +118,11 @@ protected void writeInternal(String str, HttpOutputMessage outputMessage) throws
125118
headers.setAcceptCharset(getAcceptedCharsets());
126119
}
127120
Charset charset = getContentTypeCharset(headers.getContentType());
128-
StreamUtils.copy(str, charset, outputMessage.getBody());
121+
byte[] strBytes = str.getBytes(charset);
122+
if (!headers.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
123+
headers.setContentLength(strBytes.length);
124+
}
125+
StreamUtils.copy(strBytes, outputMessage.getBody());
129126
}
130127

131128

0 commit comments

Comments
 (0)