Skip to content

Commit 4a68c44

Browse files
committed
Update content-length when reconstructing body
Closes gh-32471
1 parent e702733 commit 4a68c44

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

spring-web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -242,7 +242,7 @@ private static boolean isFormPost(HttpServletRequest request) {
242242
* from the body, which can fail if any other code has used the ServletRequest
243243
* to access a parameter, thus causing the input stream to be "consumed".
244244
*/
245-
private static InputStream getBodyFromServletRequestParameters(HttpServletRequest request) throws IOException {
245+
private InputStream getBodyFromServletRequestParameters(HttpServletRequest request) throws IOException {
246246
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
247247
Writer writer = new OutputStreamWriter(bos, FORM_CHARSET);
248248

@@ -268,7 +268,12 @@ private static InputStream getBodyFromServletRequestParameters(HttpServletReques
268268
}
269269
writer.flush();
270270

271-
return new ByteArrayInputStream(bos.toByteArray());
271+
byte[] bytes = bos.toByteArray();
272+
if (bytes.length > 0 && getHeaders().containsKey(HttpHeaders.CONTENT_LENGTH)) {
273+
getHeaders().setContentLength(bytes.length);
274+
}
275+
276+
return new ByteArrayInputStream(bytes);
272277
}
273278

274279
}

spring-web/src/test/java/org/springframework/http/server/ServletServerHttpRequestTests.java

+13
Original file line numberDiff line numberDiff line change
@@ -203,4 +203,17 @@ void getFormBodyWhenQueryParamsAlsoPresent() throws IOException {
203203
assertThat(result).as("Invalid content returned").isEqualTo(content);
204204
}
205205

206+
@Test // gh-32471
207+
void getFormBodyWhenNotEncodedCharactersPresent() throws IOException {
208+
mockRequest.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
209+
mockRequest.setMethod("POST");
210+
mockRequest.addParameter("name", "Test");
211+
mockRequest.addParameter("lastName", "Test@er");
212+
mockRequest.addHeader("Content-Length", 26);
213+
214+
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
215+
assertThat(result).isEqualTo("name=Test&lastName=Test%40er".getBytes(StandardCharsets.UTF_8));
216+
assertThat(request.getHeaders().getContentLength()).isEqualTo(result.length);
217+
}
218+
206219
}

0 commit comments

Comments
 (0)