本指南将引导您完成创建使用 RESTful Web 服务的应用程序的过程。
你将建造什么
您将构建一个应用程序,该应用程序使用 SpringRestTemplate
在https://quoters.apps.pcfone.io/api/random检索随机 Spring Boot 报价。
你需要什么
- 约15分钟
- 最喜欢的文本编辑器或 IDE
- JDK 1.8或更高版本
- Gradle 4+或Maven 3.2+
- 您还可以将代码直接导入 IDE:
- 弹簧工具套件 (STS)
- IntelliJ IDEA
如何完成本指南
像大多数 Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会得到工作代码。
要从头开始,请继续从 Spring Initializr 开始。
要跳过基础知识,请执行以下操作:
- 下载并解压缩本指南的源存储库,或使用Git克隆它:
git clone https://github.com/spring-guides/gs-consuming-rest.git
- 光盘进入
gs-consuming-rest/initial
- 跳转到获取 REST 资源。
完成后,您可以对照中的代码检查结果gs-consuming-rest/complete
。
从 Spring Initializr 开始
您可以使用这个预先初始化的项目并单击 Generate 下载 ZIP 文件。此项目配置为适合本教程中的示例。
手动初始化项目:
- 导航到https://start.spring.io。该服务提取应用程序所需的所有依赖项,并为您完成大部分设置。
- 选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。
- 单击Dependencies并选择Spring Web。
- 单击生成。
- 下载生成的 ZIP 文件,该文件是根据您的选择配置的 Web 应用程序的存档。
如果您的 IDE 具有 Spring Initializr 集成,您可以从您的 IDE 完成此过程。
你也可以从 Github 上 fork 项目并在你的 IDE 或其他编辑器中打开它。
获取 REST 资源
完成项目设置后,您可以创建一个使用 RESTful 服务的简单应用程序。
一个 RESTful 服务已经在https://quoters.apps.pcfone.io/api/random建立起来。它随机获取有关 Spring Boot 的引用并将它们作为 JSON 文档返回。
如果您通过 Web 浏览器或 curl 请求该 URL,您会收到如下所示的 JSON 文档:
这很容易,但在通过浏览器或 curl 获取时并不是非常有用。
以编程方式使用 REST Web 服务的更有用的方法。为了帮助您完成这项任务,Spring 提供了一个方便的模板类,称为RestTemplate. RestTemplate
使与大多数 RESTful 服务的交互成为单行咒语。它甚至可以将该数据绑定到自定义域类型。
首先,您需要创建一个域类来包含您需要的数据。以下清单显示了Quote
可以用作域类的类:
src/main/java/com/example/consumingrest/Quote.java
这个简单的 Java 类有一些属性和匹配的 getter 方法。它带有@JsonIgnoreProperties
来自 Jackson JSON 处理库的注释,表示任何未绑定在此类型中的属性都应被忽略。
要将您的数据直接绑定到您的自定义类型,您需要将变量名称指定为与从 API 返回的 JSON 文档中的键完全相同。如果您的 JSON 文档中的变量名称和键不匹配,您可以使用@JsonProperty
注释来指定 JSON 文档的确切键。(此示例将每个变量名称与 JSON 键匹配,因此此处不需要该注释。)
您还需要一个额外的类来嵌入内部引用本身。该类Value
满足了这一需求,并显示在以下清单 (at src/main/java/com/example/consumingrest/Value.java
) 中:
这使用相同的注释,但映射到其他数据字段。
完成申请
Initalizr 创建一个带有main()
方法的类。以下清单显示了 Initializr 创建的类(at src/main/java/com/example/consumingrest/ConsumingRestApplication.java
):
现在您需要向ConsumingRestApplication
该类添加一些其他内容,以使其显示来自我们 RESTful 源的引用。您需要添加:
- 一个记录器,用于将输出发送到日志(在此示例中为控制台)。
- A
RestTemplate
,它使用 Jackson JSON 处理库来处理传入的数据。 - A在启动
CommandLineRunner
时运行RestTemplate
(并因此获取我们的报价)。
以下清单显示了完成的ConsumingRestApplication
类 (at src/main/java/com/example/consumingrest/ConsumingRestApplication.java
):
运行应用程序
您可以使用 Gradle 或 Maven 从命令行运行应用程序。您还可以构建一个包含所有必要依赖项、类和资源的单个可执行 JAR 文件并运行它。构建可执行 jar 可以在整个开发生命周期、跨不同环境等中轻松地作为应用程序交付、版本化和部署服务。
如果您使用 Gradle,则可以使用./gradlew bootRun
. 或者,您可以使用构建 JAR 文件./gradlew build
,然后运行 JAR 文件,如下所示:
如果您使用 Maven,则可以使用./mvnw spring-boot:run
. 或者,您可以使用构建 JAR 文件,./mvnw clean package
然后运行该 JAR 文件,如下所示:
此处描述的步骤创建了一个可运行的 JAR。您还可以构建经典的 WAR 文件。
您应该看到类似于以下的输出,但带有随机引用:
如果您看到显示为 的错误,Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote]则可能是您处于无法连接到后端服务的环境中(如果您可以访问它,它将发送 JSON)。也许您是公司代理的幕后黑手。尝试将http.proxyHost和http.proxyPort系统属性设置为适合您的环境的值。
概括
恭喜!您刚刚使用 Spring Boot 开发了一个简单的 REST 客户端。