Question

I'm currently building a REST client which has pretty much the exact same code as in the Consuming a RESTful Web Service guide. This simple example works excellently when receiving valid JSON responses but since I'm also developing the webservice I wanted to be able to capture the raw response contents in case the response isn't valid JSON (without having to send the request twice).

So basically the guide boils down to this code:

RestTemplate restTemplate = new RestTemplate();
Page page = restTemplate.getForObject("http://graph.facebook.com/gopivotal", Page.class);
System.out.println("Name:    " + page.getName());
System.out.println("About:   " + page.getAbout());
System.out.println("Phone:   " + page.getPhone());
System.out.println("Website: " + page.getWebsite());

And is based on this class:

package hello;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Page {

    private String name;
    private String about;
    private String phone;
    private String website;

    public String getName() {
        return name;
    }

    public String getAbout() {
        return about;
    }

    public String getPhone() {
        return phone;
    }

    public String getWebsite() {
        return website;
    }

}

Now imagine that the response is NOT valid JSON (due to a mistake in the webservice or so) or even that the response type is not application/json, how can I log the response body as plain text? I.e. how can I access the response body as plain text when this line fails:

Page page = restTemplate.getForObject("http://graph.facebook.com/gopivotal", Page.class);

PS: I came across this question - which never got answered - and though I'm not sure, I think the actual intent of that code corresponds with my question as well.

Was it helpful?

Solution

You have to implement your custom ResponseErrorHandler and plug it into your RestTemplate bean.

something like:

public class LogResponseErrorHandler implements ResponseErrorHandler {
...
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        logResponse(response.getBody());
    }
...
}

an article about the concrete usage of ResponseErrorHandler:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top