SpringBoot系列: 与Spring Rest服务交互数据
不管是单体应用还是微服务应用, 现在都流行Restful风格, 下图是一个比较典型的使用rest的应用架构, 该应用不仅使用database数据源, 而且用到了一个Weather微服务, 另一方面, 该应用也是通过rest方式为web UI 或其他微服务应用提供服务.

=============================
通过Postman 插件测试Rest接口
=============================
之前使用postman 插件调试rest接口总报 415 Unsupported Media Type错误, 原因是: HEADERS中必须设置Content-type为application/json, 后台才能顺利接收到参数. 见下图截图.
{
"timestamp": "2018-09-07T06:49:57.620+0000",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'text/plain;charset=UTF-8' not supported",
"path": "/books"
}

=============================
与 Rest 服务交互的几个环节
=============================
一. Spring 后台与其他Rest服务的数据交互
Spring 提供了 RestTemplate 类, 方便和其他Rest服务交互数据
二. 在web response中 返回 json 数据
对于Restful的视图方法, 其返回类型可以是 ResponseEntity<T> 或者 ResponseEntity<List<T>>, Spring会自动将返回值转换为json格式. 如果要输出多个对象的复合体json, 可以在java中定义一个Wrapper类组合多个Pojo类, 然后返回这个Wrapper对象即可.
三. 接收 web Request 中的 json 数据
视图方法的 @RequestBody 注释参数可以是Map类型, 也可以是Pojo类型. 如果是Pojo类型, Spring就自动完成json->object的转换, 如果是map类型, Spring就自动完成kv映射. 如果json数据是多个object的某种组合, 我们可以在java中定义一个Wrapper类组合多个Pojo类, 专门接收 Request 中的json数据.
=============================
示例代码
=============================
Pojo代码:
class Office {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
class Car {
private String brand;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
/*
* Boss 类是 Office 和 Office 类的组合
*/
class Boss {
private Car car;
private Office office;
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Office getOffice() {
return office;
}
public void setOffice(Office office) {
this.office = office;
}
}
Controller和主函数代码:
@SpringBootApplication
@RestController
public class Demo1Application { // 示例: 一个对象的json response
// 测试url为 http://localhost:8080/oneOffice
// 结果为 {"address":"address1"}
@ResponseBody
@RequestMapping(value = "/oneOffice", method = RequestMethod.GET)
public ResponseEntity<Office> oneOffice() {
Office office = new Office();
office.setAddress("address1");
return new ResponseEntity<Office>(office, HttpStatus.OK);
} // 示例: 一个集合的json response
// 测试url为 http://localhost:8080/offices
// 结果为 [{"address":"address1"},{"address":"address2"}]
@ResponseBody
@RequestMapping(value = "/offices", method = RequestMethod.GET)
public ResponseEntity<List<Office>> offices() {
List<Office> offices = new ArrayList<Office>();
Office office1 = new Office();
office1.setAddress("address1");
Office office2 = new Office();
office2.setAddress("address2");
offices.add(office1);
offices.add(office2);
return new ResponseEntity<List<Office>>(offices, HttpStatus.OK);
} // 示例: 一个简单对象的 Post 示例
// 测试url为 http://localhost:8080/offices
// 提交的data为 { "address": "address1" }
@RequestMapping(value = "/offices", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public String createOffice(@RequestBody Office office) {
if (office != null && office.getAddress() != null) {
return "OK";
} else {
return "Empty";
}
} // 示例: 一个组合对象的 response 示例
// 测试url为 http://localhost:8080/oneBoss
// 结果为 {"car":null,"office":{"address":"address1"}}
@RequestMapping(value = "/oneBoss", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Boss> oneBoss() {
Office office = new Office();
office.setAddress("address1");
Boss objectWrapper = new Boss();
objectWrapper.setOffice(office);
return new ResponseEntity<Boss>(objectWrapper, HttpStatus.OK);
} // 示例: 一个组合对象的 Post 示例
// 测试url为 http://localhost:8080/bosses
// 提交的data为 {"car":null,"office":{"address":"address1"}}
@RequestMapping(value = "/bosses", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public String createBoss(@RequestBody Boss boss) {
if (boss != null && boss.getOffice() != null
&& boss.getOffice().getAddress() != null) {
return "OK";
} else {
return "Empty";
}
} public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
=========================
参考
=========================
https://www.leveluplunch.com/java/tutorials/014-post-json-to-spring-rest-webservice/
https://javabeat.net/rest-api-best-practices/
https://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration
截图来自: https://github.com/hamvocke/testing-microservices-ebook/blob/master/testing-microservices.adoc
SpringBoot系列: 与Spring Rest服务交互数据的更多相关文章
- SpringBoot系列之Spring Data Jpa集成教程
SpringBoot系列之Spring Data Jpa集成教程 Spring Data Jpa是属于Spring Data的一个子项目,Spring data项目是一款集成了很多数据操作的项目,其下 ...
- SpringBoot系列之Spring容器添加组件方式
SpringBoot系列之Spring容器添加组件方式 本博客介绍SpringBoot项目中将组件添加到Spring容器中的方法,SpringBoot项目有一个很明显的优点,就是不需要再编写xml配置 ...
- SpringBoot系列:Spring Boot使用模板引擎FreeMarker
一.Java模板引擎 模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档. 在jav ...
- SpringBoot系列:Spring Boot使用模板引擎Thymeleaf
一.Java模板引擎 模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档. 在jav ...
- SpringBoot系列:Spring Boot使用模板引擎JSP
一.Java模板引擎 模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档. 在jav ...
- SpringBoot系列:Spring Boot集成Spring Cache,使用RedisCache
前面的章节,讲解了Spring Boot集成Spring Cache,Spring Cache已经完成了多种Cache的实现,包括EhCache.RedisCache.ConcurrentMapCac ...
- SpringBoot系列:Spring Boot集成Spring Cache,使用EhCache
前面的章节,讲解了Spring Boot集成Spring Cache,Spring Cache已经完成了多种Cache的实现,包括EhCache.RedisCache.ConcurrentMapCac ...
- SpringBoot系列:Spring Boot定时任务Spring Schedule
Spring Schedule是Spring提供的定时任务框架,相较于Quartz,Schedule更加简单易用,在中小型应用中,对于大部分需求,Schedule都可以胜任. 一.Spring Sch ...
- SpringBoot系列:Spring Boot集成定时任务Quartz
一.关于Quartz Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用.在java企业级应用中,Q ...
随机推荐
- 数论细节梳理&模板
初阶 扩展欧拉 \(k\ge\varphi(m)\)时,\(b^k\equiv b^{k\%\varphi(m)+\varphi(m)}(\bmod m\)) 扩展CRT 推式子合并同余方程. htt ...
- Codeforces Round #402 (Div. 2) D. String Game
D. String Game time limit per test 2 seconds memory limit per test 512 megabytes input standard inpu ...
- Electron一学习资源收集和练习demo
1.近日为了做项目查资料学习electron,简直头都要炸了,就官方的electron-quick-start的例子进行了基本的练习之后,不断的查资料终于发现一些有用的demo来看源代码学习,一遍看代 ...
- C# Winfrom常用的几个公共控件
ComboBox控件的使用方法: //首先写好查询方法,实例化对象, NationData nd = new NationData(); List<Nation> NN = new Lis ...
- strut2 的数据验证
数据验证 用户的输入验证,必须做,且工作量巨大. 1.验证的方式 客户端验证:javascript 服务端验证:逻辑验证(我们的代码) 注意:如果客户端和服务端二选一的话,服务器端的不能省. 实际开发 ...
- ajax多表单序列化
今天在修一个后台接收参数为空值的bug 找了好久才发现原来是form表单合拼参数的时候把参数给搞没了 (我也不知道为什么啊—_—!) //对表单进行Json对象序列化 (function($){ $. ...
- MFC调用halcon生成的cpp内容
打开VS,文件——新建——项目——Visual C++——MFC——MFC应用程序,注意下图,其他默认.窗体1个Button.1个Picture Control [VS配置Halcon] 1.若hal ...
- php递归函数中使用return的注意事项
php递归函数中使用return的时候会碰到无法正确返回想要的值得情况,如果不明白其中的原因,很难找出错误的,就下面的具体例子来说明一下吧: function test($i){ $i-=4; if( ...
- 100.Same Tree(E)
100. same tree 100. Same Tree Given two binary trees, write a function to check if they are the same ...
- (Bash博弈)51nod1067 Bash游戏 V2
1067 Bash游戏 V2 有一堆石子共有N个.A B两个人轮流拿,A先拿.每次只能拿1,3,4颗,拿到最后1颗石子的人获胜.假设A B都非常聪明,拿石子的过程中不会出现失误.给出N,问最后谁能赢得 ...