How to get responseBody from WebClientResponseException?

240 views Asked by At

I have a web client in a Java Springboot project which throws a org.springframework.web.reactive.function.client.WebClientResponseException.BadRequest exception when an invalid param is sent in a GET request. However, calling the api directly from another client (like Insomnia) returns 400 BAD REQUEST with body:

{
    "errors": {
        "gameId": [
            "Parameter gameId must contain a list of valid Game IDs"
        ]
    },
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|f31f0b04-483ddfa36420387d."
}

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClientResponseException.html has several methods to get the response body such:

  • getResponseBodyAs(Class<E> targetType)
  • getResponseBodyAs(ParameterizedTypeReference<E> targetType)
  • getResponseBodyAsByteArray()
  • getResponseBodyAsString()
  • getResponseBodyAsString(Charset defaultCharset) But with no one of them I can get the response body as String, Json, Map, POJO, etc.

Example:

e.getResponseBodyAsString(StandardCharsets.UTF_8);

Returns:

�$��n�@E�r�e� �4�J��G]�3�4���AB�ghv��=�熬*����F���'-����q�^&�8A�%�J1�W���3����zf��dv�}U�H�.�
N�X�lL���]7/��E�Von�,h��d�'QEyY�g
Q�gU�������u����?�}�6l�.�:�m��C����ux���:}�

Even when headers has:

Content-Type:"application/json; charset=utf-8"

Any idea or suggestion?


Edit:

Result of getResponseBodyAsByteArray():

[31, -117, 8, 0, 0, 0, 0, 0, 0, 3, 36, -114, -53, 110, -62, 64, 12, 69, 127, -59, 114, -73, 101, -14, 32, -76, 52, -21, 74, 21, -85, -78, 71, 93, -72, 51, 14, -116, 52, -119, -111, -57, 65, 66, -108, 127, 103, 104, 118, -66, -42, 61, -70, -25, -122, -84, 42, -102, -79, -65, -31, -111, 70, -34, 5, -20, 15, -72, 39, 45, -73, -79, -62, -14, -125, 113, -50, 6, 94, 38, -93, 56, 1, 65, -118, 37, -54, 0, 23, 74, 49, -64, 87, -23, -64, -18, 51, -29, -49, -3, 21, -19, 122, 102, -20, -15, 100, 118, -50, 125, 85, -103, 72, -54, 46, -78, 13, 78, -12, 88, -99, 108, 76, -107, 14, -2, -67, 93, 55, 47, -103, -67, 69, -103, 86, 111, 110, -29, 26, 44, 104, -76, -12, 100, -65, 39, 6, 81, 24, 69, 121, 89, -96, 103, 13, 22, 81, 16, -17, 103, 85, 14, -82, 16, -39, -56, -26, -30, -34, -43, 117, -63, -107, -4, -65, 63, -2, 125, -124, 54, 108, -102, 46, -84, 58, -30, 109, -88, 27, -10, 67, -35, -3, -74, -76, 117, 120, 127, 0, 0, 0, -1, -1, 3, 0, -52, 58, 26, 125, -14, 0, 0, 0]
0

There are 0 answers