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.
Posting JSON With postForObject. RestTemplate's postForObject method creates a new resource by posting an object to the given URI template. It returns the result as automatically converted to the type specified in the responseType parameter.
You can use the annotation @JsonRootName to specify the root element in your response. So try this: @JsonIgnoreProperties(ignoreUnknown = true) @JsonRootName(value ="result") public class User { public User(){ } private boolean admin; .... }
For example, the method getForObject() will perform a GET and return an object. getForEntity() : executes a GET request and returns an object of ResponseEntity class that contains both the status code and the resource as an object. getForObject() : similar to getForEntity() , but returns the resource directly.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With