How to use RestTemplate with multiple response types?

You could implement a custom ResponseErrorHandler that converts an erroneous response into a RuntimeException. Http Message to POJO conversion could be done by re-using the messageConverter(s) the RestTemplate#setMessageConverters is using.

Here is an example that utilizes this.


As you would figure, the problem is that the backend should return you errors with HTTP error codes, that's what they are there for.

But as you said, you don't have control over the backend so what you can do is first get it as a String

ResponseEntity<String> dto = restTemplate.postForObject(url, postData, String.class);

Then you can attempt to parse the string response as a MainDTO with either Jackson or Gson (whatever you have in your project, which you should, because I believe Spring's RestTemplate uses either on of them internally) with a try/catch and if it fails, then you try with to parse it with your ErrorDto.

Update

Oh, I just read that it was an XML service, not a JSON on, the approach above is still valid, but instead of using Jackson or Gson, you can use SimpleXML (http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#deserialize) which allows you to deserialize XML in an "easy" way, you just need to annotate your models with their annotations which are described in their tutorials and examples.

This Spring's example (http://spring.io/guides/gs/consuming-rest-xml-android/) might also provide an insight in how to use SimpleXML.


I had the same problem, I solved it like this:

I created a Response class and inside I put the two response objects. I have noted all three classes with

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)

ResponseEntity <Response> responseEntity = restTemplate.postForEntity (url, request, Response.class);
Object res = responseEntity.getBody ();

if (res! = null) {
    if (res instanceof MainDTO) {
        ...
    } else if (res instanceof ErrorDTO) {
        ...
    }
}

Hope it's useful!