1 介绍

REST(RepresentationalState Transfer)是Roy Fielding 提出的一个描述互联系统架构风格的名词。REST定义了一组体系架构原则,您可以根据这些原则设计以系统资源为中心的Web 服务,包括使用不同语言编写的客户端如何通过 HTTP处理和传输资源状态。
为什么称为 REST?Web本质上由各种各样的资源组成,资源由URI 唯一标识。浏览器(或者任何其它类似于浏览器的应用程序)将展示出该资源的一种表现方式,或者一种表现状态。如果用户在该页面中定向到指向其它资源的链接,则将访问该资源,并表现出它的状态。这意味着客户端应用程序随着每个资源表现状态的不同而发生状态转移,也即所谓REST。

2 示例

2.1 依赖引入

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.3.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. <dependencies>
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-web</artifactId>
  11. </dependency>
  12. <dependency>
  13. <groupId>com.alibaba</groupId>
  14. <artifactId>fastjson</artifactId>
  15. <version>1.2.73</version>
  16. </dependency>
  17. </dependencies>

2.2 application.yml

  1. server:
  2. port: 9000
  3. servlet:
  4. context-path: /

2.3 准备

为了方便测试,需要准备一个Web项目,我这边准备使用之前的项目,参考链接:https://www.yuque.com/siyijianjun/hikktn/ytgswt

2.4 配置

  1. package com.hikktn.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.http.client.ClientHttpRequestFactory;
  5. import org.springframework.http.client.SimpleClientHttpRequestFactory;
  6. import org.springframework.web.client.RestTemplate;
  7. /**
  8. * RestTemplate配置
  9. */
  10. @Configuration
  11. public class RestTemplateConfig {
  12. @Bean
  13. public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
  14. return new RestTemplate(factory);
  15. }
  16. @Bean
  17. public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
  18. SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  19. // 超时设置
  20. factory.setReadTimeout(5000);//ms
  21. factory.setConnectTimeout(15000);//ms
  22. return factory;
  23. }
  24. }

2.5 返回类

  1. package com.hikktn.domain;
  2. public class ResponseCode {
  3. private int code;
  4. private String message;
  5. private Object data;
  6. public int getCode() {
  7. return code;
  8. }
  9. public void setCode(int code) {
  10. this.code = code;
  11. }
  12. public String getMessage() {
  13. return message;
  14. }
  15. public void setMessage(String message) {
  16. this.message = message;
  17. }
  18. public Object getData() {
  19. return data;
  20. }
  21. public void setData(Object data) {
  22. this.data = data;
  23. }
  24. public ResponseCode() {
  25. }
  26. public ResponseCode(int code, Object data) {
  27. this.code = code;
  28. this.data = data;
  29. }
  30. public ResponseCode(int code, String message, Object data) {
  31. this.code = code;
  32. this.message = message;
  33. this.data = data;
  34. }
  35. }

2.6 控制器

  1. package com.hikktn.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.hikktn.domain.ResponseCode;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.*;
  6. import org.springframework.web.bind.annotation.*;
  7. import org.springframework.web.client.RestTemplate;
  8. import java.net.URI;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. @RestController
  12. public class TestController {
  13. @Autowired
  14. private RestTemplate restTemplate;
  15. @GetMapping("getGroovyData")
  16. @ResponseBody
  17. public ResponseCode getGroovyData() {
  18. /**
  19. * getForObject
  20. *
  21. * 参数1 要请求的地址的url 必填项
  22. * 参数2 响应数据的类型 是String 还是 Map等 必填项
  23. * 参数3 请求携带参数 选填
  24. *
  25. * getForObject 方法的返回值就是 被调用接口响应的数据
  26. */
  27. String result = restTemplate.getForObject("http://localhost:8080/todo/getAll", String.class);
  28. return new ResponseCode(200, "ok!", result);
  29. }
  30. @GetMapping("getGroovyByIdForData")
  31. @ResponseBody
  32. public ResponseCode getGroovyByIdForData(@RequestParam("id") Integer id) {
  33. String result = restTemplate.getForObject("http://localhost:8080/todo/getById?todoId={1}", String.class, id);
  34. return new ResponseCode(200, "ok!", result);
  35. }
  36. @GetMapping("getGroovyByIdForEntity")
  37. @ResponseBody
  38. public ResponseCode getGroovyByIdForEntity(@RequestParam("id") Integer id) {
  39. /**
  40. * getForEntity 方法
  41. * 参数1 要请求的地址的url 必填项
  42. * 参数2 响应数据的类型 是String 还是 Map等 必填项
  43. * 参数3 请求携带参数 选填
  44. *
  45. * 返回值类型为 ResponseEntity
  46. *
  47. * 可以通过ResponseEntity 获取响应的数据,响应的状态码等信息
  48. */
  49. ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/todo/getById?todoId=" + id, String.class);
  50. return new ResponseCode(response.getStatusCodeValue(), response.getBody());
  51. }
  52. @GetMapping("getGroovyByIdForMap")
  53. @ResponseBody
  54. public ResponseCode getGroovyByIdForMap(@RequestParam("id") Integer id) {
  55. Map<String, Integer> map = new HashMap<>();
  56. map.put("todoId", id);
  57. String result = restTemplate.getForObject("http://localhost:8080/todo/getById?todoId={todoId}", String.class, map);
  58. return new ResponseCode(200, "ok!", result);
  59. }
  60. @PostMapping(value = "saveGroovyForObject")
  61. public ResponseCode saveGroovyForObject(@RequestBody JSONObject jsonObject) {
  62. /**
  63. * postForObject 返回值为响应的数据
  64. * 参数1 要请求地址的url
  65. * 参数2 通过LinkedMultiValueMap对象封装请求参数 模拟表单参数,封装在请求体中
  66. * 参数3 响应数据的类型
  67. */
  68. HttpHeaders headers = new HttpHeaders();
  69. headers.setContentType(MediaType.APPLICATION_JSON);
  70. HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);
  71. // LinkedMultiValueMap<String, Object> request = new LinkedMultiValueMap<>();
  72. // request.set("task", task);
  73. // request.set("isCompleted", isCompleted);
  74. String result = restTemplate.postForObject("http://localhost:8080/todo/save", request, String.class);
  75. return new ResponseCode(200, "ok!", result);
  76. }
  77. @PostMapping("saveGroovyForLocation")
  78. public ResponseCode saveGroovyForLocation(@RequestBody JSONObject jsonObject){
  79. HttpHeaders headers = new HttpHeaders();
  80. headers.setContentType(MediaType.APPLICATION_JSON);
  81. HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);
  82. /**
  83. * postForLocation 这个API和前两个都不一样
  84. *
  85. * 登录or注册都是post请求,而这些操作完成之后呢?大部分都是跳转到别的页面去了,这种场景下,就可以使用 postForLocation 了,提交数据,并获取返回的URI
  86. * 响应参数要跳转的地址
  87. */
  88. URI uri = restTemplate.postForLocation("http://localhost:8080/todo/save", request);
  89. System.out.println(uri);
  90. return new ResponseCode(200,uri);
  91. }
  92. @PutMapping("updateGroovyExchange")
  93. public ResponseCode updateGroovyExchange(@RequestBody JSONObject jsonObject){
  94. HttpHeaders headers = new HttpHeaders();
  95. headers.setContentType(MediaType.APPLICATION_JSON);
  96. HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);
  97. ResponseEntity<String> result = restTemplate.exchange("http://localhost:8080/todo/update", HttpMethod.PUT, request, String.class);
  98. return new ResponseCode(200,"ok!",result);
  99. }
  100. @DeleteMapping("deleteGroovy")
  101. public ResponseCode deleteGroovy(@RequestParam("id") Integer id){
  102. restTemplate.delete("http://localhost:8080/todo/del?todoId={todoId}",id);
  103. return new ResponseCode(200,"ok!");
  104. }
  105. }

2.7 测试

2.7.1 getGroovyData方法

image.png

2.7.2 getGroovyByIdForData方法

image.png

2.7.3 getGroovyByIdForEntity方法

image.png

2.7.4 getGroovyByIdForMap方法

image.png

2.7.5 saveGroovyForObject方法

image.png

2.7.6 saveGroovyForLocation方法

image.png
image.png

2.7.7 updateGroovyExchange方法

image.png
image.png

2.7.8 deleteGroovy方法

image.png
image.png