|
1 | 1 | /*
|
2 |
| - * Copyright 2002-2019 the original author or authors. |
| 2 | + * Copyright 2002-2021 the original author or authors. |
3 | 3 | *
|
4 | 4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | 5 | * you may not use this file except in compliance with the License.
|
@@ -43,6 +43,7 @@ public class WebClientResponseException extends WebClientException {
|
43 | 43 |
|
44 | 44 | private final HttpHeaders headers;
|
45 | 45 |
|
| 46 | + @Nullable |
46 | 47 | private final Charset responseCharset;
|
47 | 48 |
|
48 | 49 | @Nullable
|
@@ -97,7 +98,7 @@ public WebClientResponseException(String message, int statusCode, String statusT
|
97 | 98 | this.statusText = statusText;
|
98 | 99 | this.headers = (headers != null ? headers : HttpHeaders.EMPTY);
|
99 | 100 | this.responseBody = (responseBody != null ? responseBody : new byte[0]);
|
100 |
| - this.responseCharset = (charset != null ? charset : StandardCharsets.ISO_8859_1); |
| 101 | + this.responseCharset = charset; |
101 | 102 | this.request = request;
|
102 | 103 | }
|
103 | 104 |
|
@@ -139,10 +140,26 @@ public byte[] getResponseBodyAsByteArray() {
|
139 | 140 | }
|
140 | 141 |
|
141 | 142 | /**
|
142 |
| - * Return the response body as a string. |
| 143 | + * Return the response content as a String using the charset of media type |
| 144 | + * for the response, if available, or otherwise falling back on |
| 145 | + * {@literal ISO-8859-1}. Use {@link #getResponseBodyAsString(Charset)} if |
| 146 | + * you want to fall back on a different, default charset. |
143 | 147 | */
|
144 | 148 | public String getResponseBodyAsString() {
|
145 |
| - return new String(this.responseBody, this.responseCharset); |
| 149 | + return getResponseBodyAsString(StandardCharsets.ISO_8859_1); |
| 150 | + } |
| 151 | + |
| 152 | + /** |
| 153 | + * Variant of {@link #getResponseBodyAsString()} that allows specifying the |
| 154 | + * charset to fall back on, if a charset is not available from the media |
| 155 | + * type for the response. |
| 156 | + * @param defaultCharset the charset to use if the {@literal Content-Type} |
| 157 | + * of the response does not specify one. |
| 158 | + * @since 5.3.7 |
| 159 | + */ |
| 160 | + public String getResponseBodyAsString(Charset defaultCharset) { |
| 161 | + return new String(this.responseBody, |
| 162 | + (this.responseCharset != null ? this.responseCharset : defaultCharset)); |
146 | 163 | }
|
147 | 164 |
|
148 | 165 | /**
|
|
0 commit comments