7.1.4 请求 POST 资源

现在,假设向 Taco Cloud 菜单添加了一种新 Ingredient。向 .../ingredients 端点发起 HTTP POST 请求就能实现添加,这个请求的请求体重需要包含 Ingredient 数据。RestTemplate 有三种发送 POST 请求的方法,每种方法都有相同的重载变量来指定 URL。如果想在 POST 请求后收到新创建的 Ingredient 资源,可以像这样使用 postForObject():

public Ingredient createIngredient(Ingredient ingredient) {
    return rest.postForObject("http://localhost:8080/ingredients",
                             ingredient,
                             Ingredient.class);
}

postForObject() 方法的这种形式采用 String 作为 URL 规范,要发送到服务器的对象以及响应主体应该绑定到的域类型。虽然在本例中没有利用它,但第四个参数可以是 URL 变量值的 Map 或要替换到 URL 中的参数的变量列表。

如果客户对新创建的资源的位置有更多的需求,那么可以调用 postForLocation():

public URI createIngredient(Ingredient ingredient) {
    return rest.postForLocation("http://localhost:8080/ingredients",
                                ingredient);
}

注意,postForLocation() 的工作方式与 postForObject() 非常相似,只是它返回的是新创建资源的 URI,而不是资源对象本身。返回的 URI 派生自响应的 Location 头信息。如果同时需要位置和响应负载,可以调用 postForEntity():

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();
}

虽然 RestTemplate 方法的用途不同,但是它们的使用方式非常相似。这使得你很容易精通 RestTemplate 并在客户端代码中使用它。

另一方面,如果使用的 API 在其响应中包含超链接,那么 RestTemplate 就没有那么有用了。当然可以使用 RestTemplate 获取更详细的资源数据,并处理其中包含的内容和链接,但是这样做并不简单。在使用 RestTemplate 调用超媒体 API 时,与其挣扎,不如将注意力转移到为这类事情创建的客户端库 —— Traverson。

results matching ""

    No results matching ""