Browse Source

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
pull/35933/head
Brian Clozel 3 weeks ago
parent
commit
a4b3111928
  1. 5
      spring-web/src/main/java/org/springframework/http/HttpEntity.java
  2. 10
      spring-web/src/test/java/org/springframework/http/HttpEntityTests.java

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

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

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

@ -136,4 +136,14 @@ class HttpEntityTests { @@ -136,4 +136,14 @@ class HttpEntityTests {
.isEmpty();
}
@Test
void headerAreMutable() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
String body = "foo";
HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);
httpEntity.getHeaders().setContentType(MediaType.APPLICATION_JSON);
}
}

Loading…
Cancel
Save