S
S
Spring 实战(第五版)
搜索文档…
S
S
Spring 实战(第五版)
Spring 实战(第 5 版)
第一部分 Spring 基础
第 1 章 Spring 入门
第 2 章 开发 Web 应用程序
第 3 章 处理数据
第 4 章 Spring 安全
第 5 章 使用配置属性
第二部分 集成 Spring
第 6 章 创建 REST 服务
第 7 章 调用 REST 服务
7.1 使用 RestTemplate 调用 REST 端点
7.1.1 请求 GET 资源
7.1.2 请求 PUT 资源
7.1.3 请求 DELETE 资源
7.1.4 请求 POST 资源
7.2 使用 Traverson 引导 REST API
7.3 小结
第 8 章 发送异步消息
第 9 章 集成 Spring
第三部分 响应式 Spring
第 10 章 Reactor 介绍
第 11 章 开发响应式 API
第 12 章 响应式持久化数据
第四部分 云原生 Spring
第 13 章 服务发现
第 14 章 配置管理
第 15 章 处理失败和时延
第五部分 部署Spring
第 16 章 使用 SpringBoot Actuator
第 17 章 管理 Spring
第 18 章 使用 JMX 监控 Spring
第 19 章 部署 Spring
由
GitBook
提供支持
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。
以前
7.1.3 请求 DELETE 资源
下一个
7.2 使用 Traverson 引导 REST API
最近更新
2yr ago
复制链接