Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use RestTemplate with multiple response types?

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.

like image 713
membersound Avatar asked Mar 04 '16 13:03

membersound


People also ask

Is RestTemplate multithreaded?

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.

Why RestTemplate is deprecated?

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.

Does RestTemplate support all HTTP methods?

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.


2 Answers

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!

like image 137
David Querci Avatar answered Oct 04 '22 15:10

David Querci


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.

like image 35
fateddy Avatar answered Oct 04 '22 16:10

fateddy