Update content-length when reconstructing body

Closes gh-32471
This commit is contained in:
rstoyanchev 2024-03-28 14:17:41 +01:00
parent e702733c7b
commit 4a68c44a27
2 changed files with 21 additions and 3 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -242,7 +242,7 @@ public class ServletServerHttpRequest implements ServerHttpRequest {
* from the body, which can fail if any other code has used the ServletRequest
* to access a parameter, thus causing the input stream to be "consumed".
*/
private static InputStream getBodyFromServletRequestParameters(HttpServletRequest request) throws IOException {
private InputStream getBodyFromServletRequestParameters(HttpServletRequest request) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
Writer writer = new OutputStreamWriter(bos, FORM_CHARSET);
@ -268,7 +268,12 @@ public class ServletServerHttpRequest implements ServerHttpRequest {
}
writer.flush();
return new ByteArrayInputStream(bos.toByteArray());
byte[] bytes = bos.toByteArray();
if (bytes.length > 0 && getHeaders().containsKey(HttpHeaders.CONTENT_LENGTH)) {
getHeaders().setContentLength(bytes.length);
}
return new ByteArrayInputStream(bytes);
}
}

View File

@ -203,4 +203,17 @@ class ServletServerHttpRequestTests {
assertThat(result).as("Invalid content returned").isEqualTo(content);
}
@Test // gh-32471
void getFormBodyWhenNotEncodedCharactersPresent() throws IOException {
mockRequest.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
mockRequest.setMethod("POST");
mockRequest.addParameter("name", "Test");
mockRequest.addParameter("lastName", "Test@er");
mockRequest.addHeader("Content-Length", 26);
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
assertThat(result).isEqualTo("name=Test&lastName=Test%40er".getBytes(StandardCharsets.UTF_8));
assertThat(request.getHeaders().getContentLength()).isEqualTo(result.length);
}
}