7.1 使用RestTemplate 调用REST 端点
7.1 使用RestTemplate 调用REST 端点
从客户的角度来看,与
为了避免这样的样板代码,
表
方法 | 描述 |
---|---|
delete(…) | 对指定 |
exchange(…) | 对 |
execute(…) | 对 |
getForEntity(…) | 发送 |
getForObject(…) | 发送 |
headForHeaders(…) | 发送 |
optionsForAllow(…) | 发送 |
patchForObject(…) | 发送 |
postForEntity(…) | 将数据 |
postForLocation(…) | 将数据 |
postForObject(…) | 将数据 |
put(…) | 将资源数据 |
除了
- 一种是接受一个
String 作为URL 规范,在一个变量参数列表中指定URL 参数。 - 一种是接受一个
String 作为URL 规范,其中的URL 参数在Map<String, String> 中指定。 - 一种是接受
java.net.URI 作为URL 规范,不支持参数化URL 。
一旦了解了
要使用
RestTemplate rest = new RestTemplate();
或是将它声明为一个
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
让我们通过查看支持四种主要
7.1.1 请求GET 资源
假设想从
public Ingredient getIngredientById(String ingredientId) {
return rest.getForObject("http://localhost:8080/ingredients/{id}",
Ingredient.class, ingredientId);
}
这里使用的是{id}
占位符。虽然在本例中只有一个
或者,可以使用映射来指定
public Ingredient getIngredientById(String ingredientId) {
Map<String, String> urlVariables = new HashMap<>();
urlVariables.put("id", ingredientId);
return rest.getForObject("http://localhost:8080/ingredient/{id}",
Ingredient.class, urlVariables);
}
在这个例子中,{id}
占位符被键为
使用
public Ingredient getIngredientById(String ingredientId) {
Map<String,String> urlVariables = new HashMap<>();
urlVariables.put("id", ingredientId);
URI url = UriComponentsBuilder
.fromHttpUrl("http://localhost:8080/ingredients/{id}")
.build(urlVariables);
return rest.getForObject(url, Ingredient.class);
}
这里的
例如,假设除了
public Ingredient getIngredientById(String ingredientId) {
ResponseEntity<Ingredient> responseEntity =
rest.getForEntity("http://localhost:8080/ingredients/{id}",
Ingredient.class, ingredientId);
log.info("Fetched time: " +
responseEntity.getHeaders().getDate());
return responseEntity.getBody();
}
7.1.2 请求PUT 资源
对于发送
假设想要用来自一个新的
public void updateIngredient(Ingredient ingredient) {
rest.put("http://localhost:8080/ingredients/{id}",
ingredient,
ingredient.getId());
}
这里
7.1.3 请求DELETE 资源
假设
public void deleteIngredient(Ingredient ingredient) {
rest.delete("http://localhost:8080/ingredients/{id}",
ingredient.getId());
}
在本例中,仅将
7.1.4 请求POST 资源
现在,假设向.../ingredients
端点发起
public Ingredient createIngredient(Ingredient ingredient) {
return rest.postForObject("http://localhost:8080/ingredients",
ingredient,
Ingredient.class);
}
如果客户对新创建的资源的位置有更多的需求,那么可以调用
public URI createIngredient(Ingredient ingredient) {
return rest.postForLocation("http://localhost:8080/ingredients",
ingredient);
}
注意,
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();
}
虽然
另一方面,如果使用的