原文

参考链接

翻译如何调用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是推荐的做法。

所以,总的来说就是:

  1. 进入main方法
  2. 看到第一个Bean,执行这个方法,通过自动注入的RestTemplateBuilder生成一个RestTemplate。
  3. 看到第二个Bean,是一个CommandLineRunner,Spring就执行这个run方法,使用上一步得到的RestTemplate

有几个问题:

  1. 如果两个Bean的顺序变一下,或者指定其他的Order,会怎么样?测试了一下,没有关系。所以Bean需要的参数应该是统一获取。

生成一个可执行的jar文件

执行mvn clean package,生成一个可执行的jar文件。

然后用java -jar ***.jar就可以运行了。

小结

就是试验了一下RestTemplate如何用。最基础的入门。

[SpringBoot guides系列翻译]调用RESTfulWebService的更多相关文章

  1. [SpringBoot guides系列翻译]通过JDBC和Spring访问关系数据库

    原文 参考链接 hikaricp Spring Boot JDBC Starter Spring Boot Starter Parent h2 database introduction Autowi ...

  2. [SpringBoot guides系列翻译]调度任务

    原文 调度任务 用spring实现一个任务调度. 你将做的 你将做一个应用每5秒钟打印当前时间,用@Scheduled注解. 你需要啥 15分钟 文本编辑器或者IDE JDK1.8+ Gradle4+ ...

  3. [SpringBoot guides系列翻译]SpringBoot构建RESTful程序入门

    原文地址 构建一个RESTful的WebService 这个指南将带你用Spring创建一个RESTful的helloworld程序. 你将完成 在下面地址上创建一个接收http get请求的服务 h ...

  4. [SpingBoot guides系列翻译]Redis的消息订阅发布

    Redis的消息 部分参考链接 原文 CountDownLatch 概述 目的 这节讲的是用Redis来实现消息的发布和订阅,这里会使用Spring Data Redis来完成. 这里会用到两个东西, ...

  5. [SpingBoot guides系列翻译]文件上传

    文件上传 这节的任务是做一个文件上传服务. 概况 参考链接 原文 thymeleaf spring-mvc-flash-attributes @ControllerAdvice 你构建的内容 分两部分 ...

  6. SpringBoot基础系列-SpringCache使用

    原创文章,转载请标注出处:<SpringBoot基础系列-SpringCache使用> 一.概述 SpringCache本身是一个缓存体系的抽象实现,并没有具体的缓存能力,要使用Sprin ...

  7. 【SpringBoot基础系列】手把手实现国际化支持实例开发

    [SpringBoot基础系列]手把手实现国际化支持实例开发 国际化的支持,对于app开发的小伙伴来说应该比价常见了:作为java后端的小伙伴,一般来讲接触国际化的机会不太多,毕竟业务开展到海外的企业 ...

  8. SpringBoot基础系列-使用日志

    原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9996897.html SpringBoot基础系列-使用日志 概述 SpringBoot ...

  9. SpringBoot基础系列-使用Profiles

    原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9996884.html SpringBoot基础系列-使用Profile 概述 Profi ...

随机推荐

  1. 学习React Native必看的几个开源项目

    学习React native ,分享几个不错的开源项目,相信你学完之后,一定会有所收获.如果还没有了解RN的同学们可以参考手把手教你React Native 实战之开山篇<一> 1.Fac ...

  2. 容器化的Apache服务并监控

    1:基础容器编译部署apache 1.1:pull一个ubuntu 16.04的镜像 sudo docker pull ubuntu:16.04 1.2:运行容器 sudo docker run -d ...

  3. python里面的xlrd模块详解(一)

    那我就一下面积个问题对xlrd模块进行学习一下: 1.什么是xlrd模块? 2.为什么使用xlrd模块? 3.怎样使用xlrd模块? 1.什么是xlrd模块? python操作excel主要用到xlr ...

  4. djanogo class meta

    1.指定字段名: 在定义字段的时候,增加参数db_column='real_field': 2.指定表名: 在model的class中,添加Meta类,在Meta类中指定表名db_table 例如在某 ...

  5. 从壹开始前后端分离【 .NETCore2.1 +Vue 2 +AOP+DI】框架之一 || 前言

    缘起 作为一个.Net攻城狮已经4年有余了,一直不温不火,正好近来项目不是很忙,闲得无聊,搞一搞新技术,一方面是打发无聊的时间,一方面也是督促自己该学习辣!身边的大神都转行的转行,加薪的加薪,本人比较 ...

  6. Redis in .NET Core 入门:(3) Hash

    第1篇:https://www.cnblogs.com/cgzl/p/10294175.html 第2篇 String:https://www.cnblogs.com/cgzl/p/10297565. ...

  7. WinForm加载外部类库项目的集成开发模式

    在项目开发中有一定的团队用到了Nuget.Coding:但是这用起来还是不太方方便,在Winform中呢,我们可以把一个人的项目当作一个类库项目,因为它生成的是一个dll文件,也就是单一文件,拥有了它 ...

  8. 『Lucas定理以及拓展Lucas』

    Lucas定理 在『组合数学基础』中,我们已经提出了\(Lucas\)定理,并给出了\(Lucas\)定理的证明,本文仅将简单回顾,并给出代码. \(Lucas\)定理:当\(p\)为质数时,\(C_ ...

  9. mvc、mvp和mvvm

    一.MVC 设计图: 可能由于MVP.MVVM的兴起,MVC在android中的应用变得越来越少了,但MVC是基础,理解好MVC才能更好的理解MVP,MVVM.因为后两种都是基于MVC发展而来的. 1 ...

  10. PHP 技能精进之 PHP-FPM 多进程模型

    PHP-FPM 提供了更好的 PHP 进程管理方式,可以有效控制内存和进程.可以平滑重载PHP配置.那么当我们谈论 PHP-FPM 多进程模型的时候,作为 PHPer 的你了解多少呢? 首先,让我们一 ...