Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 84175c3

Browse files
committedApr 17, 2024·
Fix HttpHeaders setContentLength method
1 parent f21e05a commit 84175c3

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed
 

Diff for: ‎spring-web/src/main/java/org/springframework/http/HttpHeaders.java

+6
Original file line numberDiff line numberDiff line change
@@ -969,8 +969,14 @@ public Locale getContentLanguage() {
969969
/**
970970
* Set the length of the body in bytes, as specified by the
971971
* {@code Content-Length} header.
972+
* @param contentLength content length (greater than or equal to zero)
973+
* @throws IllegalArgumentException if the content length is negative
974+
* @see <a href="https://www.rfc-editor.org/rfc/rfc2616#section-14.13">RFC 2616, section 14.13</a>
972975
*/
973976
public void setContentLength(long contentLength) {
977+
if (contentLength < 0){
978+
throw new IllegalArgumentException("Content-Length must be a non-negative number");
979+
}
974980
set(CONTENT_LENGTH, Long.toString(contentLength));
975981
}
976982

Diff for: ‎spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java

+12
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,18 @@ void contentLength() {
154154
assertThat(headers.getFirst("Content-Length")).as("Invalid Content-Length header").isEqualTo("42");
155155
}
156156

157+
@Test
158+
void setContentLengthWithNegativeValue() {
159+
assertThatIllegalArgumentException().isThrownBy(() ->
160+
headers.setContentLength(-1));
161+
}
162+
163+
@Test
164+
void getContentLengthReturnsMinusOneForAbsentHeader() {
165+
headers.remove(HttpHeaders.CONTENT_LENGTH);
166+
assertThat(headers.getContentLength()).isEqualTo(-1);
167+
}
168+
157169
@Test
158170
void contentType() {
159171
MediaType contentType = new MediaType("text", "html", StandardCharsets.UTF_8);

0 commit comments

Comments
 (0)
Please sign in to comment.