19
votes

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.

2
@Sotirios Delimanolis. Fine, so what's should I use ?Zamboo
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.Sotirios Delimanolis
Or rather, take a look at this stackoverflow.com/questions/3322381/…. Implement your own ResponseExtractor and call restTemplate.execute(...)Sotirios Delimanolis
@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
I was wrong, just take a look at the various answers or my last comment.Sotirios Delimanolis

2 Answers

44
votes

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();
3
votes

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.