Skip to content

Commit a4b3111

Browse files
committed
Make HttpEntity headers mutables
Since its inception, instantiating an `HttpEntity` makes its `HttpHeaders` read-only. While immutability is an interesting design principle, here we shouldn't enforce this. For example, developers can expect to instantiate a `ResponseEntity` and still mutate its headers. Closes gh-35888
1 parent 4c4161c commit a4b3111

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

spring-web/src/main/java/org/springframework/http/HttpEntity.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ public HttpEntity(HttpHeaders headers) {
102102
*/
103103
public HttpEntity(@Nullable T body, @Nullable HttpHeaders headers) {
104104
this.body = body;
105-
this.headers = HttpHeaders.readOnlyHttpHeaders(headers != null ? headers : new HttpHeaders());
105+
this.headers = (headers != null) ? headers : new HttpHeaders();
106106
}
107107

108108
/**
@@ -123,8 +123,7 @@ public HttpEntity(MultiValueMap<String, String> headers) {
123123
*/
124124
@Deprecated(since = "7.0", forRemoval = true)
125125
public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers) {
126-
this.body = body;
127-
this.headers = HttpHeaders.readOnlyHttpHeaders(headers != null ? new HttpHeaders(headers) : new HttpHeaders());
126+
this(body, (headers != null) ? new HttpHeaders(headers) : new HttpHeaders());
128127
}
129128

130129

spring-web/src/test/java/org/springframework/http/HttpEntityTests.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,4 +136,14 @@ void mutateEmptyInstanceHeaders() {
136136
.isEmpty();
137137
}
138138

139+
@Test
140+
void headerAreMutable() {
141+
HttpHeaders headers = new HttpHeaders();
142+
headers.setContentType(MediaType.TEXT_PLAIN);
143+
String body = "foo";
144+
HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);
145+
httpEntity.getHeaders().setContentType(MediaType.APPLICATION_JSON);
146+
147+
}
148+
139149
}

0 commit comments

Comments
 (0)