7.3.4 POSTing resource data
Now let’s say that you add a new ingredient to the Taco Cloud menu. An HTTP POST request to the …/ingredients endpoint with ingredient data in the request body will make that happen. RestTemplate has three ways of sending a POST request, each of which has the same overloaded variants for specifying the URL. If you wanted to receive the newly created Ingredient resource after the POST request, you’d use postForObject() like this:
public Ingredient createIngredient(Ingredient ingredient) {
return rest.postForObject("http://localhost:8080/ingredients",
ingredient, Ingredient.class);
}This variant of the postForObject() method takes a String URL specification, the object to be posted to the server, and the domain type that the response body should be bound to. Although you aren’t taking advantage of it in this case, a fourth parameter could be a Map of the URL variable value or a variable list of parameters to substitute into the URL.
If your client has more need for the location of the newly created resource, then you can call postForLocation() instead, as shown here:
public java.net.URI createIngredient(Ingredient ingredient) {
return rest.postForLocation("http://localhost:8080/ingredients",
ingredient);
}Notice that postForLocation() works much like postForObject(), with the exception that it returns a URI of the newly created resource instead of the resource object itself. The URI returned is derived from the response’s Location header. In the off chance that you need both the location and response payload, you can call postForEntity() like so:
public Ingredient createIngredient(Ingredient ingredient) {
ResponseEntity<Ingredient> responseEntity =
rest.postForEntity("http://localhost:8080/ingredients",
ingredient,
Ingredient.class);
log.info("New resource created at " +
responseEntity.getHeaders().getLocation());
return responseEntity.getBody();
}Although the methods of RestTemplate differ in their purpose, they’re quite similar in how they’re used. This makes it easy to become proficient with RestTemplate and use it in your client code.
