Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate post response

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.

like image 561
Zamboo Avatar asked May 06 '13 15:05

Zamboo


People also ask

How do you post data with RestTemplate?

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.

How do you parse a RestTemplate response?

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; .... }

What is difference between getForObject and getForEntity?

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.


2 Answers

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();
like image 113
hyness Avatar answered Sep 28 '22 10:09

hyness


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.

like image 3
Nikola Yovchev Avatar answered Sep 28 '22 11:09

Nikola Yovchev