How to use RestTemplate with multiple response types?

二次信任 提交于 2019-12-04 07:42:27

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.

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.

I have the same problem so I have an abstract class that describes the error. All of my Json classes then extended the abstract error class. So the response object is populated with entity data and an error that I could check easily.

I don't particularly like this solution but as I immediately transform the Json object into an application data object it doesn't feel too bad.

Using Instanceof

MyObject1 a=null;
MyObject2 b=null;
ResponseEntity<Object>response=template.exchange(builder.build().encode().toUri(),HttpMethod.GET,entity, Object.class);
if (response.getBody() instanceof MyObject1)
    a= (MyObject1) response.getBody();
else if(response.getBody() instanceof MyObject2)
    b= (MyObject2) response.getBody();

I tried Alfredo's solution but I got an Exception because of Object.class:

Method threw 'org.springframework.web.client.HttpClientErrorException' exception.

If you use a different class, it would be casted and you wouldn't be able to use instance of.

Using following code solved my problem:

String xml = restTemplate.getForObject(url, String.class, uriVariables);
JAXBContext jaxbContext = JAXBContext.newInstance();
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringSource xmlStr = new StringSource(xml);
Object o = jaxbUnmarshaller.unmarshal((Source) xmlStr);
if (o instanceof VonAZRAZRBestaetigungMeldung090098) {
    // ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!