1

I want to get the object as well as the HTTP response of one api into another in Spring code. For that I am using a rest template and I am getting the desired Object from it successfully.

But I want to fetch HTTP response also for the respective api. What should I do to get this?

RestTemplate restTemplate = new RestTemplate();
Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
System.out.println("quote "+quote);
System.out.println(quote.getType());
log.info(quote.toString());
aUserHimself
  • 1,589
  • 2
  • 17
  • 26
Amit Gujarathi
  • 1,090
  • 1
  • 12
  • 25

1 Answers1

4

getForObject method of RestTemplate only gets the result. If you're interest in the status code you should invode exchange which returns a ResponseEntity which has a getStatusCode method.

RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Quote> response= restTemplate.exchange ("http://gturnquist-quoters.cfapps.io/api/random", HttpMethod.GET, null, Quote.class);
    Quote quote = response..getBody();
    System.out.println("status "+response..getStatusCode());
    System.out.println("quote "+quote);
    System.out.println(quote.getType());
StephaneM
  • 4,779
  • 1
  • 16
  • 33