19

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Zamboo
  • 513
  • 2
  • 8
  • 18
  • @Sotirios Delimanolis. Fine, so what's should I use ? – Zamboo May 06 '13 at 15:29
  • Check the link I posted, the Apache HTTP Components. This shows an example: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/HttpClient.html You lose some, you gain some. – Sotirios Delimanolis May 06 '13 at 15:30
  • Or rather, take a look at this http://stackoverflow.com/questions/3322381/spring-resttemplate-behavior-when-handling-responses-with-a-status-of-no-content. Implement your own `ResponseExtractor` and call `restTemplate.execute(...)` – Sotirios Delimanolis May 06 '13 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. – Zamboo May 06 '13 at 15:34
  • I was wrong, just take a look at the various answers or my last comment. – Sotirios Delimanolis May 06 '13 at 15:34

2 Answers2

46

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();
hyness
  • 4,785
  • 1
  • 22
  • 24
  • How do I get the headers if I want them in an errorcase? – simonides Jun 25 '14 at 20:03
  • what if I dont know response class ? – Normal Jul 07 '16 at 13:51
  • 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. – hyness Jul 08 '16 at 14:51
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.

Nikola Yovchev
  • 9,498
  • 4
  • 46
  • 72