Skip to content

Commit 57b8100

Browse files
committed
Copy headers map in RestClientResponseException to ensure serializability
This commit ensures that the HttpHeaders used are serializable by making a copy. Closes gh-31787
1 parent 7432a96 commit 57b8100

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

spring-web/src/main/java/org/springframework/web/client/RestClientResponseException.java

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
import org.springframework.http.HttpStatusCode;
2828
import org.springframework.lang.Nullable;
2929
import org.springframework.util.Assert;
30+
import org.springframework.util.LinkedMultiValueMap;
31+
import org.springframework.util.MultiValueMap;
3032

3133
/**
3234
* Common base class for exceptions that contain actual HTTP response data.
@@ -88,11 +90,27 @@ public RestClientResponseException(
8890
super(message);
8991
this.statusCode = statusCode;
9092
this.statusText = statusText;
91-
this.responseHeaders = headers;
93+
this.responseHeaders = copyHeaders(headers);
9294
this.responseBody = (responseBody != null ? responseBody : new byte[0]);
9395
this.responseCharset = (responseCharset != null ? responseCharset.name() : null);
9496
}
9597

98+
/**
99+
* Copies the given headers, because the backing map might not be
100+
* serializable.
101+
*/
102+
@Nullable
103+
private static HttpHeaders copyHeaders(@Nullable HttpHeaders headers) {
104+
if (headers != null) {
105+
MultiValueMap<String, String> result = new LinkedMultiValueMap<>(headers.size());
106+
headers.forEach((name, values) -> values.forEach(value -> result.add(name, value)));
107+
return HttpHeaders.readOnlyHttpHeaders(result);
108+
}
109+
else {
110+
return null;
111+
}
112+
}
113+
96114

97115
/**
98116
* Return the HTTP status code.

spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ public void handleError() throws Exception {
7474
assertThatExceptionOfType(HttpClientErrorException.class)
7575
.isThrownBy(() -> handler.handleError(response))
7676
.withMessage("404 Not Found: \"Hello World\"")
77-
.satisfies(ex -> assertThat(ex.getResponseHeaders()).isSameAs(headers));
77+
.satisfies(ex -> assertThat(ex.getResponseHeaders()).isEqualTo(headers));
7878
}
7979

8080
@Test

0 commit comments

Comments
 (0)