21

I'm not familiar with Spring RestTemplate.

But for this project I have to use Spring RestTemplate to send a POST call to consume a rest api.

I'm using this code:

String restCall = restTemplate.postForObject(url+restParm, null, String.class);

This is working fine.

I would like to retriveve the HTTP status code (E.g: 200 OK.). How could I do that ? Thanks.

5
  • @Sotirios Delimanolis. Fine, so what's should I use ? Commented May 6, 2013 at 15:29
  • Check the link I posted, the Apache HTTP Components. This shows an example: hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/… You lose some, you gain some. Commented May 6, 2013 at 15:30
  • Or rather, take a look at this stackoverflow.com/questions/3322381/…. Implement your own ResponseExtractor and call restTemplate.execute(...) Commented May 6, 2013 at 15:32
  • @Sotirios: Thanks for the tip, but I really need to use RestTemplate, because I have to manage some security that are foreseen to be used through this API. Commented May 6, 2013 at 15:34
  • I was wrong, just take a look at the various answers or my last comment. Commented May 6, 2013 at 15:34

2 Answers 2

48

You use the postForEntity method as follows...

ResponseEntity<String> response = restTemplate.postForEntity(url+restParm, null, String.class);
HttpStatus status = response.getStatusCode();
String restCall = response.getBody();
Sign up to request clarification or add additional context in comments.

3 Comments

How do I get the headers if I want them in an errorcase?
what if I dont know response class ?
The response will always be available as a String, as in my example. If the response is in a format that can be bound to an object, such as json or xml, you may specify that as the response type and Spring will bind it to the class for you. See the Spring documentation for more information about binding.
3

It will be pretty weird if RestTemplate couldn't get the response,as others have suggested. It is simply not true.

You just use the postForEntity method which returns a

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/http/ResponseEntity.html

And as the documentation suggests, the response entity has the status.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.