Consuming a RESTful Web Service

This guide walks you through the process of creating an application that consumes a RESTful web service.
What You Will Build

You will build an application that uses Spring’s RestTemplate to retrieve a random Spring Boot quotation at https://gturnquist-quoters.cfapps.io/api/random.
What You Need

About 15 minutes

A favorite text editor or IDE

JDK 1.8 or later

Gradle 4+ or Maven 3.2+

You can also import the code straight into your IDE:

    Spring Tool Suite (STS)

    IntelliJ IDEA

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Starting with Spring Initializr.

To skip the basics, do the following:

Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-consuming-rest.git

cd into gs-consuming-rest/initial

Jump ahead to Fetching a REST Resource.

When you finish, you can check your results against the code in gs-consuming-rest/complete.
Starting with Spring Initializr

For all Spring applications, you can start with the Spring Initializr. The Initializr offers a fast way to pull in all the dependencies you need for an application and does a lot of the set up for you. Because this example needs to be nothing more than a web application, you need to include only the Web dependency. The following image shows the Initializr set up for this sample project:
initializr
The preceding image shows the Initializr with Maven chosen as the build tool. You can also use Gradle. It also shows values of com.example and consuming-rest as the Group and Artifact, respectively. You will use those values throughout the rest of this sample.

The following listing shows the pom.xml file created when you choose Maven:

<?xml version="1.0" encoding="UTF-8"?>


4.0.0

org.springframework.boot
spring-boot-starter-parent
2.1.7.RELEASE


com.example
consuming-rest
0.0.1-SNAPSHOT
consuming-rest
Demo project for Spring Boot

<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>

The following listing shows the build.gradle file created when you choose 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’
}

These build files can be this simple because spring-boot-starter-web includes everything you need to build a web application, including the Jackson classes you need to work with JSON.
Fetching a REST Resource

With project setup complete, you can create a simple application that consumes a RESTful service.

A RESTful service has been stood up at https://gturnquist-quoters.cfapps.io/api/random. It randomly fetches quotations about Spring Boot and returns them as JSON documents.

If you request that URL through a web browser or curl, you receive a JSON document that looks something like this:

{
type: “success”,
value: {
id: 10,
quote: “Really loving Spring Boot, makes stand alone Spring apps easy.”
}
}

That is easy enough but not terribly useful when fetched through a browser or through curl.

A more useful way to consume a REST web service is programmatically. To help you with that task, Spring provides a convenient template class called RestTemplate. RestTemplate makes interacting with most RESTful services a one-line incantation. And it can even bind that data to custom domain types.

First, you need to create a domain class to contain the data that you need. The following listing shows the Quote class, which you can use as your domain class:

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 +
‘}’;
}
}

This simple Java class has a handful of properties and matching getter methods. It is annotated with @JsonIgnoreProperties from the Jackson JSON processing library to indicate that any properties not bound in this type should be ignored.

To directly bind your data to your custom types, you need to specify the variable name to be exactly the same as the key in the JSON document returned from the API. In case your variable name and key in JSON doc do not match, you can use @JsonProperty annotation to specify the exact key of the JSON document. (This example matches each variable name to a JSON key, so you do not need that annotation here.)

You also need an additional class, to embed the inner quotation itself. The Value class fills that need and is shown in the following listing (at 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 + ‘’’ +
‘}’;
}
}

This uses the same annotations but maps onto other data fields.
Finishing the Application

The Initalizr creates a class with a main() method. The following listing shows the class the Initializr creates (at src/main/java/com/example/consumingrest/ConsumingRestApplication.java):

package com.example.consumingrest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ConsumingRestApplication {

public static void main(String[] args) {
	SpringApplication.run(ConsumingRestApplication.class, args);
}

}

Now you need to add a few other things to the ConsumingRestApplication class to get it to show quotations from our RESTful source. You need to add:

A logger, to send output to the log (the console, in this example).

A RestTemplate, which uses the Jackson JSON processing library to process the incoming data.

A CommandLineRunner that runs the RestTemplate (and, consequently, fetches our quotation) on startup.

The following listing shows the finished ConsumingRestApplication class (at 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());
	};
}

}

Running the Application

You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

If you use Gradle, you can run the application by using ./gradlew bootRun. Alternatively, you can build the JAR file by using ./gradlew build and then run the JAR file, as follows:

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

If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:

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

The steps described here create a runnable JAR. You can also build a classic WAR file.

You should see output similar to the following but with a random quotation:

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.’}}

If you see an error that reads, Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote], it is possible that you are in an environment that cannot connect to the backend service (which sends JSON if you can reach it). Maybe you are behind a corporate proxy. Try setting the http.proxyHost and http.proxyPort system properties to values appropriate for your environment.

Summary

Congratulations! You have just developed a simple REST client by using Spring Boot.

translate:
翻译:

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

你将建造什么

您将在https://gturnquist-quoters.cfapps.io/api/random上构建一个使用Spring的restemplate检索随机Spring引导报价的应用程序。

你需要什么

大约15分钟

最喜欢的文本编辑器或IDE

JDK 1.8或更高版本

Gradle 4+或Maven 3.2+

您还可以直接将代码导入到IDE中:

Spring工具套件(STS)

智力观念

如何完成本指南

与大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。不管怎样,你最终都会使用代码。

要从头开始,请继续使用Spring初始化器。

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

下载并解压缩此指南的源存储库,或使用Git:Git clone https://github.com/spring-guides/gs-consuming-rest.Git进行克隆

cd进入gs消耗休息/初始

跳到前面获取REST资源。

完成后,可以对照gs中消耗rest/complete的代码检查结果。

从Spring初始化器开始

对于所有Spring应用程序,可以从Spring初始化器开始。initializer提供了一种快速的方法来获取应用程序所需的所有依赖项,并为您进行了很多设置。因为这个例子只需要一个web应用程序,所以只需要包含web依赖项。下图显示了为此示例项目设置的初始值设定项:

初始化程序

上图显示了选择Maven作为构建工具的初始化器。你也可以用格雷德。它还分别显示com.example和将rest作为组和工件使用的值。您将在本示例的其余部分中使用这些值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值