16.4.9 在 POST 请求后获取资源位置

如果要同时接收所发送的资源和响应头,postForEntity() 方法是很便利的。但通常你并不需要将资源发送回来(毕竟,将其发送到服务器端是第一位的)。如果你真正需要的是 Location 头信息的值, 那么使用 RestTemplate 的 postForLocation() 方法会更简单。

类似于其他的 POST 方法,postForLocation() 会在 POST 请求的请求体中发送一个资源到服务器端。但是,响应不再是相同的资源对象,postForLocation() 的响应是新创建资源的位置。它有如下三个方法签名:

URI postForLocation(String url, Object request, Object... uriVariables) throws RestClientException;

URI postForLocation(String url, Object request, Map<String, ?> uriVariables) throws RestClientException;

URI postForLocation(URI url, Object request) throws RestClientException;

为了展示 postForLocation(),让我们再次 POST 一个 Spitter。这次,我们希望在返回中包含资源的 URL:

public String postSpitter(Spitter spitter) {
  RestTemplate rest = new RestTemplate();
  return rest.postForLocation("http://localhost:8080/spittr-api/spitters",
    spitter).toString();
}

在这里,我们以 String 的形式将目标 URL 传递进来,还有要 POST 的 Spitter 对象(在本示例中没有 URL 参数)。在创建资源后,如果服务端在响应的 Location 头信息中返回新资源的 URL,接下来 postForLocation() 会以 String 的格式返回该 URL。

Last updated