Skip to content

Commit

Permalink
Update content-length when reconstructing body
Browse files Browse the repository at this point in the history
Closes gh-32471
  • Loading branch information
rstoyanchev committed Apr 9, 2024
1 parent e702733 commit 4a68c44
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -242,7 +242,7 @@ private static boolean isFormPost(HttpServletRequest request) {
* 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);

Expand All @@ -268,7 +268,12 @@ private static InputStream getBodyFromServletRequestParameters(HttpServletReques
}
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);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,17 @@ void getFormBodyWhenQueryParamsAlsoPresent() throws IOException {
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);
}

}

0 comments on commit 4a68c44

Please sign in to comment.