membersound
membersound

Reputation: 86915

How to use RestTemplate with different ResponseEntities?

What if a XML webservice can respond with different xml structures? Eg an <OkResponse> and an <ErrorResponse>, having completely different fields?

ResponseEntity<Response> rsp = restTemplate
        .postForEntity(url, new HttpEntity<>(xml, HEADERS), OkResponse.class);

Before sending the request, I don't know which type of response will come back. If I'm using OkResponse.class, I will get a ClassCastException if an ErrorResponse is returned.

How could I handle this?

The autogenerated beans are as follows:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({
    OkResponse.class,
    ErrorResponse.class
})
public class AbstractResponse {

}

Upvotes: 0

Views: 4935

Answers (2)

Klaus Groenbaek
Klaus Groenbaek

Reputation: 5045

RestTemplate uses Jackson for JSON serialization, and it supports inherited types though the @JsonTypeInfo annotation. But it requires that all responses have a common 'type' property. If there is no common property that all responses share, then I think you need to use the String approach, and use String.contains() to find a unique property to determine which response type it is.

Upvotes: 0

Barath
Barath

Reputation: 5283

Use String.class

    ResponseEntity<String> rsp = restTemplate
            .postForEntity(url, new HttpEntity<>(xml, HEADERS), String.class);

String responseBody = (String)rsp.getBody();

 Object response=mapper.readValue(responseBody, Class.forName(responseClass))   

Once response body is obtained. make use of service class that you want to map and convert it using jackson mapper .Made use of reflection since the entity passed can be different/dynamic

Upvotes: 3

Related Questions