SpringBoot调用RESTful Web服务
本指南将引导您完成创建使用RESTful Web服务的应用程序的过程。
你会建立什么
您将RestTemplate
在https://gturnquist-quoters.cfapps.io/api/random上构建一个使用Spring 检索随机Spring Boot引用的应用程序。
如何完成本指南
像大多数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开始
对于所有Spring应用程序,您应该从Spring Initializr开始。Initializr提供了一种快速的方法来提取应用程序所需的所有依赖项,并为您完成了许多设置。由于此示例仅需要Web应用程序,因此您仅需要包含Web依赖项。下图显示了此示例项目的Initializr设置:
上图显示了选择Maven作为构建工具的Initializr。您也可以使用Gradle。这也显示出价值com.example ,并consuming-rest 分别作为集团和神器。在本示例的其余部分中,将使用这些值。 |
以下清单显示了pom.xml
选择Maven时创建的文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>consuming-rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>consuming-rest</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
以下清单显示了build.gradle
选择Gradle时创建的文件:
plugins {
id 'org.springframework.boot' version '2.1.7.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
这些构建文件可以很简单,因为它spring-boot-starter-web
包含构建Web应用程序所需的一切,包括使用JSON所需的Jackson类。
获取REST资源
完成项目设置后,您可以创建一个使用RESTful服务的简单应用程序。
RESTful服务已在https://gturnquist-quoters.cfapps.io/api/random上站起来。它随机获取有关Spring Boot的报价,并将其作为JSON文档返回。
如果您通过网络浏览器或curl请求该URL,则会收到一个类似于以下内容的JSON文档:
{
type: "success",
value: {
id: 10,
quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
}
}
通过浏览器或curl获取时,这很容易,但并不是很有用。
使用REST Web服务的一种更有用的方法是以编程方式。为了帮助您完成该任务,Spring提供了一个名为的便捷模板类RestTemplate
。RestTemplate
使与大多数RESTful服务的交互成为一线咒语。而且它甚至可以将该数据绑定到自定义域类型。
首先,您需要创建一个域类来包含所需的数据。以下清单显示了Quote
该类,您可以将其用作域类:
src/main/java/com/example/consumingrest/Quote.java
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
@Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
这个简单的Java类具有一些属性和匹配的getter方法。它@JsonIgnoreProperties
在Jackson JSON处理库中进行了注释,以指示应忽略此类型中未绑定的任何属性。
要将数据直接绑定到自定义类型,您需要指定变量名称,使其与从API返回的JSON文档中的键完全相同。如果您的变量名称和JSON文档中的密钥不匹配,则可以使用@JsonProperty
批注指定JSON文档的确切密钥。(此示例将每个变量名与一个JSON键匹配,因此在这里不需要该注释。)
您还需要一个附加的类来嵌入内部引号本身。该Value
级满足了这一需求,并在下面的列表(在所示src/main/java/com/example/consumingrest/Value.java
):
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {
private Long id;
private String quote;
public Value() {
}
public Long getId() {
return this.id;
}
public String getQuote() {
return this.quote;
}
public void setId(Long id) {
this.id = id;
}
public void setQuote(String quote) {
this.quote = quote;
}
@Override
public String toString() {
return "Value{" +
"id=" + id +
", quote='" + quote + '\'' +
'}';
}
}
这使用相同的批注,但映射到其他数据字段。
完成申请
Initalizr使用main()
方法创建一个类。以下清单显示了Initializr创建的类(位于src/main/java/com/example/consumingrest/ConsumingRestApplication.java
):
package com.example.consumingrest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumingRestApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
}
现在,您需要向ConsumingRestApplication
该类中添加其他一些内容,以使其显示来自我们RESTful源的报价。您需要添加:
-
记录器,用于将输出发送到日志(在此示例中为控制台)。
-
A
RestTemplate
,它使用Jackson JSON处理库来处理传入的数据。 -
A 在启动时
CommandLineRunner
运行RestTemplate
(因此获取我们的报价)。
以下清单显示了完成的ConsumingRestApplication
课程(位于src/main/java/com/example/consumingrest/ConsumingRestApplication.java
):
package com.example.consumingrest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumingRestApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
};
}
}
运行应用程序
您可以使用Gradle或Maven从命令行运行该应用程序。您还可以构建一个包含所有必需的依赖项,类和资源的可执行JAR文件,然后运行该文件。构建可执行的jar使得在整个开发生命周期中,跨不同环境等等的情况下,可以轻松地将服务作为应用程序进行发行,版本化和部署。
如果使用Gradle,则可以使用运行应用程序./gradlew bootRun
。或者,您可以使用来构建JAR文件./gradlew build
,然后运行JAR文件,如下所示:
java -jar build/libs/gs-consuming-rest-0.1.0.jar
如果使用Maven,则可以使用来运行该应用程序./mvnw spring-boot:run
。或者,您可以使用来构建JAR文件,./mvnw clean package
然后运行JAR文件,如下所示:
java -jar target/gs-consuming-rest-0.1.0.jar
此处描述的步骤将创建可运行的JAR。您还可以构建经典的WAR文件。 |
您应该看到类似于以下内容的输出,但带有随机引号:
2019-08-22 14:06:46.506 INFO 42940 --- [ main] c.e.c.ConsumingRestApplication : Quote{type='success', value=Value{id=1, quote='Working with Spring Boot is like pair-programming with the Spring developers.'}}
如果您看到读为的错误,Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote] 则可能是因为您所在的环境无法连接到后端服务(如果可以访问JSON,则会发送JSON)。也许您在公司代理后面。尝试将http.proxyHost 和http.proxyPort 属性设置为适合您的环境的值。 |
摘要
恭喜你!您刚刚使用Spring Boot开发了一个简单的REST客户端。
也可以看看
以下指南也可能会有所帮助:
是否要编写新指南或为现有指南做出贡献?查看我们的贡献准则。
所有指南均以代码的ASLv2许可证和写作的Attribution,NoDerivatives创用CC许可证发布。 |