-
WebClientResponseException의 responseBodyAsString에서 한글이 깨지는 문제 해결Spring 2025. 5. 4. 15:50
갑자기 잘 읽어오던 WebClientResponseException의 responseBodyAsString 부분에서 인코딩이 올바르게되지 않아 한글이 깨져서 보였다.
처음의 구성은 다음과 같았다.
private fun parseErrorResponse(ex: WebClientResponseException): ErrorResponse { return try { val body = String(ex.responseBodyAsByteArray, StandardCharsets.UTF_8) // 바이트 배열을 UTF-8로 디코딩 objectMapper.readValue(body, ErrorResponse::class.java) } catch (e: Exception) { throw RuntimeException("올바르지 않은 응답입니다.", e) } }
다음의 글을 읽고
해결 방안을 적용해보았지만, 문제가 해결되지 않았다.
@RequestMapping(method = GET, value = "my/random/uri", produces = "application/json;charset=UTF-8") spring.http.encoding.charset=UTF-8
원인
그러다 WebClientResponseException의 코드를 확인하게 되었고, responseBodyAsString 하는 부분의 인코딩 부분이 디폴트로 ISO_8859_1로 들어감을 확인하였다.
/** * Return the response content as a String using the charset of media type * for the response, if available, or otherwise falling back on * {@literal ISO-8859-1}. Use {@link #getResponseBodyAsString(Charset)} if * you want to fall back on a different, default charset. */ public String getResponseBodyAsString() { return getResponseBodyAsString(StandardCharsets.ISO_8859_1); }
해결
WebClient에서 제공하는 다음의 메서드를 확인하여 사용하도록 변경하여 해결했다.
/** * Variant of {@link #getResponseBodyAsString()} that allows specifying the * charset to fall back on, if a charset is not available from the media * type for the response. * @param defaultCharset the charset to use if the {@literal Content-Type} * of the response does not specify one. * @since 5.3.7 */ public String getResponseBodyAsString(Charset defaultCharset) { return new String(this.responseBody, (this.responseCharset != null ? this.responseCharset : defaultCharset)); }
private fun parseErrorResponse(ex: WebClientResponseException): ErrorResponse { return try { // 제공되는 메서드를 사용하도록 변경 ‼️ val body = ex.getResponseBodyAsString(StandardCharsets.UTF_8) objectMapper.readValue(body, ErrorResponse::class.java) } catch (e: Exception) { throw AccountsDriverLicenseServerException("올바르지 않은 서버 응답입니다.", e) } }
해결 완료 ✨✨✨✨✨
'Spring' 카테고리의 다른 글