springspring-bootrest-client

How to log Spring Boot 3 httpRestClient error response.body as readable string?


Prior to asking this, I am already tried using:

log.error("fail {} ", ex.getResponseBodyAsString());

I am already attaching .defaultStatusHandler() on the restClient. which is not really helping when debugging or logging the error. What I want is a clear and readable httpResponse like what we see it on the Postman.

Currently, I doing:

aRestClient.post()
            .uri(turl)
            .body(request)
            .retrieve()
            .onStatus(httpStatusCode -> httpStatusCode.value()== 400, (req, res) -> {
                System.out.printf(Arrays.toString(res.getBody().readAllBytes()));
            })
            .body(LivinPointConvertResponse.class);

which yield:

[123, 34, 99, 111, 100, 101, 34, 58, 49, 53, 44, 34, 109, 101, 115, 115, 97, 103, 101, 83, 116, 114, 34, 58, 34, 77, 97, 97, 102, 44, 32, 74, 117, 109, 108, 97, 104, 32, 109, 105, 110, 105, 109, 117, 109, 32, 112, 101, 110, 117, 107, 97, 114, 97, 110, 32, 54, 32, 76, 105, 118, 105, 110, 39, 112, 111, 105, 110, 34, 44, 34, 115, 117, 99, 99, 101, 115, 115, 34, 58, 102, 97, 108, 115, 101, 44, 34, 100, 97, 116, 97, 34, 58, 110, 117, 108, 108, 125]

Solution

  • You should do new String() instead of Arrays.toString to retrieve a readable Response.

    I can reproduce your use case if I do:

    restClient.post().uri("/posts").contentType(MediaType.APPLICATION_JSON).body(post)
        .retrieve()
        .onStatus(httpStatusCode -> httpStatusCode.value()== 400, (req, res) -> {
            System.out.printf(Arrays.toString(res.getBody().readAllBytes()));
        })
        .toBodilessEntity();
    
    System.out.println();
    
    restClient.post().uri("/posts").contentType(MediaType.APPLICATION_JSON).body(post)
        .retrieve()
        .onStatus(httpStatusCode -> httpStatusCode.value()== 400, (req, res) -> {
            System.out.printf(new String(res.getBody().readAllBytes()));
        })
        .toBodilessEntity();
    

    My output is:

    [123, 34, 116, 105, 116, 108, ..., 125]
    {"title":"title1","content":"content1","status":"DRAFT"}