david david - 23 days ago 4x
Java Question

How to extract HTTP status code from the RestTemplate call to a URL?

I am using

to make an HTTP call to our service which returns a simple JSON response. I don't need to parse that JSON at all. I just need to return whatever I am getting back from that service.

So I am mapping that to
and returning the actual
JSON response
as a string.

RestTemplate restTemplate = new RestTemplate();

String response = restTemplate.getForObject(url, String.class);

return response;

Now the question is -

I am trying to extract
HTTP Status codes
after hitting the URL. How can I extract HTTP Status code from the above code? Do I need to make any change into that in the way I doing it currently?


This is what I have tried and I am able to get the response back and status code as well. But do I always need to set
object like below I am doing it?

RestTemplate restTemplate = new RestTemplate();

//and do I need this JSON media type for my use case?
HttpHeaders headers = new HttpHeaders();

//set my entity
HttpEntity<Object> entity = new HttpEntity<Object>(headers);

ResponseEntity<String> out = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);


Couple of question - Do I need to have
as I am just making a call to url which returns a response back, it can return either JSON or XML or simple string.


Use the RestTemplate#exchange(..) methods that return a ResponseEntity. This gives you access to the status line and headers (and the body obviously).