I'm using spring RestTemplate
for communication with a xml
webservice backend as follows:
ResponseEntity<MainDTO> dto = restTemplate.postForObject(url, postData, MainDTO.class);
Problem: the backend might either respond with MainDTO
for normal data or with ErrorDTO
in case of failures. But both with HTTP 200
.
But I don't know which object will come back before! Anyways restTemplate
requires me to pass the class
type before.
So, how could I parse the xml either to normal or the error bean?
Sidenote: I don't have any control of the webservice backend.
There, we determined that RestTemplate is thread-safe. There is therefore no reason not to share it wherever it makes sense to, ie. wherever you are using it in the same way. Your example seems like the perfect place to do so.
RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof. First, we create a Spring Boot project with the spring-boot-starter-web dependency.
Spring RestTemplate class is part of spring-web , introduced in Spring 3. We can use RestTemplate to test HTTP based restful web services, it doesn't support HTTPS protocol. RestTemplate class provides overloaded methods for different HTTP methods, such as GET, POST, PUT, DELETE etc.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With