Search code examples
spring-bootrestresttemplatecontent-type

Consume Application/pdf, Application/json rest response


I'm consuming an API that returns a pdf(application/pdf) if everything goes fine. In case of exception, it returns a application/json response. How can I consume such response? How should my response class structure look like?

I'm thinking I can use

ResponseEntity<String> response
  = restTemplate.getForEntity(fooResourceUrl, String.class);

And then convert string to pdf or json depending on the content-type in the response header. Is there a better way of doing this?


Solution

  • For the success case, you can read the PDF response as a byte array as usual:

    ResponseEntity<[]byte> response = restTemplate.getForEntity(fooResourceUrl, byte[].class);
    

    For the failure case, you can catch RestClientResponseException and read the returned JSON as a string:

    try {
       ResponseEntity<[]byte> response = restTemplate.getForEntity(fooResourceUrl, byte[].class);
    } catch (RestClientResponseException e) {
       String json = e.getResponseBodyAsString();
       [...]
    }