Fork me on GitHub
余鸢

使用RESTful Web服务

本指南将指导您完成创建使用RESTful Web服务的应用程序的过程。

What you’ll build

您将构建一个使用Spring的RestTemplate在http://gturnquist-quoters.cfapps.io/api/random检索随机Spring Boot引用的应用程序。

What you’ll need

How to complete this guide

与大多数Spring Getting Started guides一样,您可以从头开始并完成每个步骤,也可以绕过已经熟悉的基本设置步骤。 无论如何,你最终得到工作代码。

要从头开始,请继续使用 Build with Gradle

要跳过基本操作,请执行以下操作:

  • Download并解压本指南的源代码仓库,或使用Git克隆它:

    git clone https://github.com/spring-guides/gs-consuming-rest.git

  • cd into gs-consuming-rest/initial

  • 向前跳转到Fetch a REST resource

完成后,您可以根据gs-consuming-rest/complete中的代码检查结果。

Build with Gradle

首先你设置一个基本的构建脚本。 你可以使用任何你喜欢的构建系统,当使用Spring构建应用程序,但是需要使用 GradleMaven的代码包括在这里。 如果你不熟悉,请参考 Building Java Projects with GradleBuilding Java Projects with Maven

Create the directory structure

在您选择的项目目录中,创建以下子目录结构; 例如,使用mkdir -p src/main/java/hello on * nix系统:

1
2
3
4
└── src
└── main
└── java
└── hello
Create a Gradle build file

下面是 initial Gradle build file

build.gradle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-consuming-rest'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter")
compile("org.springframework:spring-web")
compile("com.fasterxml.jackson.core:jackson-databind")
testCompile("junit:junit")
}

Spring Boot gradle plugin提供了许多方便的功能:

  • 它收集类路径上的所有jar,并构建一个单独的,可运行的“über-jar”,这使得执行和传输服务更加方便。
  • 它搜索public static void main()方法来标记为可运行类。
  • 它提供了一个内置的依赖解析器,用于设置版本号以匹配Spring Boot dependencies。 你可以覆盖任何你想要的版本,但它会默认为Boot的选择的版本集。

Build with Maven

首先你设置一个基本的构建脚本。 你可以使用任何你喜欢的构建系统,当使用Spring构建应用程序,但是需要使用Maven的代码包括在这里。 如果你不熟悉Maven,请参考 Building Java Projects with Maven

Create the directory structure

在您选择的项目目录中,创建以下子目录结构; 例如,使用mkdir -p src/main/java/hello on * nix系统:

1
2
3
4
└── src
└── main
└── java
└── hello

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-consuming-rest</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Spring Boot Maven plugin提供了许多方便的功能:

  • 它收集类路径上的所有jar,并构建一个单独的,可运行的“über-jar”,这使得执行和传输服务更加方便。
  • 它搜索public static void main()方法来标记为可运行类。
  • 它提供了一个内置的依赖解析器,用于设置版本号以匹配Spring Boot dependencies。 你可以覆盖任何你想要的版本,但它会默认为Boot的选择的版本集。

Build with your IDE

Fetch a REST resource

完成项目设置后,您可以创建一个使用RESTful服务的简单应用程序。

RESTful服务已经在http://gturnquist-quoters.cfapps.io/api/random上站了起来。 它随机获取关于Spring Boot的引用,并将它们作为JSON文档返回。

如果您通过Web浏览器或curl请求该网址,您会收到一个JSON文档,如下所示:

1
2
3
4
5
6
7
{
type: "success",
value: {
id: 10,
quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
}
}

足够简单,但通过浏览器或通过curl抓取时,不是非常有用。

一种更有用的方式来消耗REST Web服务是以编程方式。 为了帮助你完成这个任务,Spring提供了一个方便的模板类RestTemplateRestTemplate使与大多数RESTful服务进行交互作为一行咒语。 它甚至可以将该数据绑定到自定义域类型。

首先,创建一个域类以包含所需的数据。

src/main/java/hello/Quote.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package hello;
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方法。 它使用来自Jackson JSON处理库的@JsonIgnoreProperties进行注释,以指示不应该忽略此类型中未绑定的任何属性。

需要一个额外的类来嵌入内部引用本身。

src/main/java/hello/Value.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package hello;
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 + '\'' +
'}';
}
}

这使用相同的注释,但简单地映射到其他数据字段。

Make the application executable

虽然可以将此服务打包为用于部署到外部应用程序服务器的传统WAR文件,但下面演示的较简单的方法创建了一个独立的应用程序。 你把一切都包装在一个可执行的JAR文件中,由一个好的老的main()方法驱动。 一路上,你使用Spring的支持将Tomcat servlet容器嵌入为HTTP运行时,而不是部署到外部实例。

现在,您可以编写使用RestTemplate从我们的Spring引导引用服务获取数据的Application类。

src/main/java/hello/Application.java

1
2
3
4
5
6
7
8
9
10
11
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
RestTemplate restTemplate = new RestTemplate();
Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
}
}

因为Jackson JSON处理库在类路径中,RestTemplate将使用它(通过message converter)将传入的JSON数据转换为Quote对象。 从那里,Quote对象的内容将被记录到控制台。

这里你只使用RestTemplate来发出HTTP GET请求。 但RestTemplate也支持其他HTTP动词,如POSTPUTDELETE

Managing the Application Lifecycle with Spring Boot

到目前为止,我们没有在我们的应用程序中使用Spring Boot,但这样做有一些优势,并不难做到。 其中一个优点是我们可能想让Spring Boot管理RestTemplate中的消息转换器,以便定制很容易声明性地添加。 为此,我们在主类上使用@SpringBootApplication,并转换main方法来启动它,就像在任何Spring Boot应用程序中一样。 最后,我们将RestTemplate移动到CommandLineRunner回调,以便在启动时由Spring Boot执行:

src/main/java/hello/Application.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package hello;
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 Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
SpringApplication.run(Application.class);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
};
}
}

RestTemplateBuilder是由Spring注入的,如果你使用它来创建一个RestTemplate,那么你将受益于在Spring Boot中使用消息转换器和请求工厂发生的所有自动配置。 我们还提取RestTemplate到一个@Bean,使它更容易测试(它可以更容易模仿这种方式)。

Build an executable JAR

您可以使用Gradle或Maven从命令行运行应用程序。 或者,您可以构建单个可执行文件,其中包含所有必需的依赖关系,类和资源,并运行它。 这使得在整个开发生命周期中,跨不同环境等等,易于将服务作为应用程序进行发布,版本和部署。

如果您使用Gradle,可以使用./gradlew bootRun运行应用程序。 或者,您可以使用./gradlew build构建JAR文件。 然后可以运行JAR文件:

1
java -jar build/libs/gs-consuming-rest-0.1.0.jar

如果使用Maven,可以使用./maven spring-boot:run运行应用程序。 或者,您可以使用./mvn clean package构建JAR文件。 然后可以运行JAR文件:

1
java -jar target/gs-consuming-rest-0.1.0.jar

上面的过程将创建一个可运行的JAR。 您还可以选择构建经典WAR文件。

您应该看到如下输出,带有随机引用:

1
2015-09-23 14:22:26.415 INFO 23613 --- [main] hello.Application : Quote{type='success', value=Value{id=12, quote='@springboot with @springframework is pure productivity! Who said in #java one has to write double the code than in other langs? #newFavLib'}}

如果您看到错误:Could not extract response: no suitable HttpMessageConverter found for response type [class hello.Quote]它可能是在一个环境中无法连接到后端服务(发送JSON,如果你可以达到它)。 也许你是在企业代理后部? 请尝试将标准系统属性http.proxyHosthttp.proxyPort设置为适合您的环境的值。

Summary

恭喜! 你刚刚使用Spring开发了一个简单的REST客户端。

翻译自:http://spring.io/guides/gs/consuming-rest/