Copy headers map in RestClientResponseException to ensure serializability

This commit ensures that the HttpHeaders used are serializable by making
 a copy.

Closes gh-31787
This commit is contained in:
Arjen Poutsma 2023-12-11 12:57:09 +01:00
parent 7432a96b48
commit 57b8100a06
2 changed files with 20 additions and 2 deletions

View File

@ -27,6 +27,8 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* Common base class for exceptions that contain actual HTTP response data.
@ -88,11 +90,27 @@ public class RestClientResponseException extends RestClientException {
super(message);
this.statusCode = statusCode;
this.statusText = statusText;
this.responseHeaders = headers;
this.responseHeaders = copyHeaders(headers);
this.responseBody = (responseBody != null ? responseBody : new byte[0]);
this.responseCharset = (responseCharset != null ? responseCharset.name() : null);
}
/**
* Copies the given headers, because the backing map might not be
* serializable.
*/
@Nullable
private static HttpHeaders copyHeaders(@Nullable HttpHeaders headers) {
if (headers != null) {
MultiValueMap<String, String> result = new LinkedMultiValueMap<>(headers.size());
headers.forEach((name, values) -> values.forEach(value -> result.add(name, value)));
return HttpHeaders.readOnlyHttpHeaders(result);
}
else {
return null;
}
}
/**
* Return the HTTP status code.

View File

@ -74,7 +74,7 @@ public class DefaultResponseErrorHandlerTests {
assertThatExceptionOfType(HttpClientErrorException.class)
.isThrownBy(() -> handler.handleError(response))
.withMessage("404 Not Found: \"Hello World\"")
.satisfies(ex -> assertThat(ex.getResponseHeaders()).isSameAs(headers));
.satisfies(ex -> assertThat(ex.getResponseHeaders()).isEqualTo(headers));
}
@Test