原文

参考链接

翻译如何调用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. BZOJ_3427_Poi2013 Bytecomputer_DP

    BZOJ_3427_Poi2013 Bytecomputer_DP Description 给定一个{-1,0,1}组成的序列,你可以进行x[i]=x[i]+x[i-1]这样的操作,求最少操作次数使其 ...

  2. mysql事务隔离级别和MVCC

    一.三种问题: 脏读(Drity Read):事务A更新记录但未提交,事务B查询出A未提交记录. 不可重复读(Non-repeatable read):在一个事务的两次查询之中数据不一致,这可能是两次 ...

  3. cannot be cast to java.lang.Comparable

    Exception in thread "main" java.lang.ClassCastException: com.myradio.People cannot be cast ...

  4. python接口自动化(十八)--重定向(Location)(详解)

    简介 在实际工作中,有些接口请求完以后会重定向到别的url,而你却需要重定向前的url.URL主要是针对虚拟空间而言,因为不是自己独立管理的服务器,所以无法正常进行常规的操作.但是自己又不希望通过主域 ...

  5. 使用github pages搭建个人博客

    一.环境准备 使用Github Pages搭建个人博客,一劳永逸,可以让我们更加专注于博客的撰写.博客的更新是通过将新建或改动的博客放在指定文件夹并推送到远程Github仓库来完成的,所以我们本地需要 ...

  6. [译]PEP 342--增强型生成器:协程

    PEP原文 : https://www.python.org/dev/peps/pep-0342/ PEP标题: Coroutines via Enhanced Generators PEP作者: G ...

  7. Asp.Net Core 轻松学-正确使用分布式缓存

    前言     本来昨天应该更新的,但是由于各种原因,抱歉,让追这个系列的朋友久等了.上一篇文章 在.Net Core 使用缓存和配置依赖策略 讲的是如何使用本地缓存,那么本篇文章就来了解一下如何使用分 ...

  8. Linux基本操作——文件相关

    一.前言 无论是IC工程师.FPGA工程师还是嵌入式软件工程师,都或多或少会接触到Linux操作系统.有很多EDA工具只有Linux版本,因此掌握基本的操作和常用命令十分必要.Linux中的数据均以文 ...

  9. Certbot为域名申请免费SSL证书

    Certbot(Let's Encrypt)是一个非盈利性认证机构通过运行互联网安全研究小组(ISRG)提供X.509 证书的传输层安全性不收取任何费用(TLS)加密.证书有效期为90天,在此期间可以 ...

  10. 快速构建SPA框架SalutJS--项目工程目录 一

    起因 刚进公司那会儿,接的是一个微信APP应用,SPA是前人搭起来的,用到的技术主要是backbone和zepto.后来那人走了,就卤煮一个人把项目接了下来.项目越是到后面,越发觉了诸多弊端,不停的增 ...