[SpringBoot guides系列翻译]调用RESTfulWebService
参考链接
翻译如何调用RESTful WebService
这节将演示如何在SpringBoot里面调用RESTful的WebService。
构建的内容
使用Spring的RestTemplate来获取https://gturnquist-quoters.cfapps.io/api/random里面返回的json数据中的quotation字段的内容。
你需要的
- 大约15min
- 喜欢的编辑器或IDE
- jdk1.8+
- Gradle4+ 或 Maven3.2+
如何完成
跟着教程演示使用Maven的方式。
创建项目结构
mkdir -p src/main/java/hello创建一个目录。
定义pom.xml文件
<?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>2.0.5.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插件。他提供了很多便捷的特性。
- 把用到的所有依赖打包成一个整体,这样方便服务的执行以及分发。
- 把public static void main()标记成可执行类。
- 提供了内置的依赖解析器用于设置相符的Spring Boot依赖的版本号。
获取REST的资源数据
项目结构设置好之后,可以通过https://gturnquist-quoters.cfapps.io/api/random获取返回的数据。它返回一个json数据,里面的quote字段内容会随机变换。
可以先通过浏览器或者curl去看一下返回的内容。
// 20190416133934
// https://gturnquist-quoters.cfapps.io/api/random
{
  "type": "success",
  "value": {
    "id": 8,
    "quote": "I don't worry about my code scaling. Boot allows the developer to peel back the layers and customize when it's appropriate while keeping the conventions that just work."
  }
}
Spring提供了一个方便的模板类,RestTemplate来通过编程的方式获取地址对应的json内容。属于一行代码的事情。你也可以把得到的内容绑定到自己的类型上。
首先,创建一个领域类用来表示这个内容。两个字段,一个String 的type,一个Value类型的value。所以至少是两个类。
src/main/java/hello/Quote.java
package hello;
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 this.value;
    }
    public void setValue(Value value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return "Quote{type='" + type + "\',value=" + value + "}";
    }
}
src/main/java/hello/Value.java
package hello;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {
    private Long id;
    @JsonProperty("quote")
    private String quote1;
    public Value() {
    }
    public Long getId() {
        return this.id;
    }
    public String getQuote() {
        return this.quote1;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public void setQuote(String quote) {
        this.quote1 = quote;
    }
    @Override
    public String toString() {
        return "Value{" + "id=" + id + ",quote='" + quote1 + '\'' + '}';
    }
}
@JsonIgnoreProperties用来表示在Jackson处理json时候需要忽略的东西。默认情况下,字段的名字需要和json里面的key是一样的,如果不一样,可以使用@JsonProperty来标记。
创建一个可执行的程序,并通过Spring boot来管理他的生命周期
打包成一个war,然后托管到一个外部的server是可以的。这里演示一种创建一个独立的可执行jar文件的方式,通过main方法执行。然后托管到Spring集成的tomcat的http运行环境,而不是一个外部的实例。
现在可以开始写Application类,并且使用RestTemplate来获取上面地址的数据。
最后完成的src/main/java/hello/Application.java是这样的
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());
        };
    }
}
有几点可以理解一下:
- Logger用的是- org.slf4j.*的,不同类型,都叫Logger的还挺多的,需要注意一下。
- Application类要注解- @SpringBootApplication用来表示是SpringBoot的。
- restTemplate方法和- run方法都加了- @Bean,就表示这个部分是由Spring里面的IoC容器控制的。
- CommondLineRunner是一个接口,他用来表示这个对应的Bean需要运行- run。如果有多个可以用- @Order注解来指定顺序。
- RestTemplateBuilder是由Spring自动注入的。用他来生成- RestTemplate是推荐的做法。
所以,总的来说就是:
- 进入main方法
- 看到第一个Bean,执行这个方法,通过自动注入的RestTemplateBuilder生成一个RestTemplate。
- 看到第二个Bean,是一个CommandLineRunner,Spring就执行这个run方法,使用上一步得到的RestTemplate
有几个问题:
- 如果两个Bean的顺序变一下,或者指定其他的Order,会怎么样?测试了一下,没有关系。所以Bean需要的参数应该是统一获取。
生成一个可执行的jar文件
执行mvn clean package,生成一个可执行的jar文件。
然后用java -jar ***.jar就可以运行了。
小结
就是试验了一下RestTemplate如何用。最基础的入门。
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号