原文

参考链接

翻译如何调用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_2039_[2009国家集训队]employ人员雇佣_ 最小割

    BZOJ_2039_[2009国家集训队]employ人员雇佣_ 最小割 Description 作为一个富有经营头脑的富翁,小L决定从本国最优秀的经理中雇佣一些来经营自己的公司.这些经理相互之间合作 ...

  2. maven+springmvc的配置

    1. 首先创建1个mavenweb项目  如果没有的话最好是去官网下载一个最新版本的eclipse  里面什么都有 maven/gradle 啥的 2. 选择路径   没啥影响 就是一个路径 默认就行 ...

  3. laravel 查询数据返回的结果

    laravel查询数据返回的结果 在插入数据库的时候,发现查询数据返回的结果是一个对象;即使是空数据 返回的不是true或者false 那么要判断该结果是否查询有结果 该如果呢? 学习源头: http ...

  4. 浅谈URL跳转与Webview安全

    学习信息安全技术的过程中,用开阔的眼光看待安全问题会得到不同的结论. 在一次测试中我用Burpsuite搜索了关键词url找到了某处url,测试一下发现waf拦截了指向外域的请求,于是开始尝试绕过.第 ...

  5. Android 8.1 源码_启动篇(二) -- 深入研究 zygote(转 Android 9.0 分析)

    前言 在Android中,zygote是整个系统创建新进程的核心进程.zygote进程在内部会先启动Dalvik虚拟机,继而加载一些必要的系统资源和系统类,最后进入一种监听状态.在之后的运作中,当其他 ...

  6. Azure Devops/Tfs 编译的时候自动修改版本号

    看到阿迪王那边出品了一个基于Azure Devops自增版本号  链接 http://edi.wang/post/2019/3/1/incremental-build-number-for-net-c ...

  7. python接口自动化(十六)--参数关联接口后传(详解)

    简介 大家对前边的自动化新建任务之后,接着对这个新建任务操作了解之后,希望带小伙伴进一步巩固胜利的果实,夯实基础.因此再在沙场实例演练一下博客园的相关接口.我们用自动化发随笔之后,要想接着对这篇随笔操 ...

  8. .NET Core微服务系列基础文章索引(目录导航Final版)

    一.为啥要总结和收集这个系列? 今年从原来的Team里面被抽出来加入了新的Team,开始做Java微服务的开发工作,接触了Spring Boot, Spring Cloud等技术栈,对微服务这种架构有 ...

  9. 【转】视频H5 video最佳实践

    原文地址:https://github.com/gnipbao/iblog/issues/11 随着 4G 的普遍以及 WiFi 的广泛使用,手机上的网速已经足够稳定和高速,以视频为主的 HTML5 ...

  10. bind、call和apply对比和使用

    最开始关于call.apply.bind函数的使用时,总是很模糊,不知道用哪一个,this指向问题等,看了一些别人的总结后有了一定的理解,所以特地记录一下: 要搞清楚call.apply.bind我们 ...