RestTemplate之增删改查

1 介绍

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

2 示例

2.1 依赖引入

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>
    </dependencies>

2.2 application.yml

server:
  port: 9000
  servlet:
    context-path: /

2.3 准备

为了方便测试,需要准备一个Web项目,我这边准备使用之前的项目,参考链接:https://blog.csdn.net/qq_41520636/article/details/119989972

2.4 配置

package com.hikktn.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate配置
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //        超时设置
        factory.setReadTimeout(5000);//ms
        factory.setConnectTimeout(15000);//ms
        return factory;
    }
}

2.5 返回类

package com.hikktn.domain;

public class ResponseCode {

    private int code;
    private String message;
    private Object data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public ResponseCode() {
    }

    public ResponseCode(int code, Object data) {
        this.code = code;
        this.data = data;
    }

    public ResponseCode(int code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
}

2.6 控制器

package com.hikktn.controller;

import com.alibaba.fastjson.JSONObject;
import com.hikktn.domain.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@RestController
public class TestController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("getGroovyData")
    @ResponseBody
    public ResponseCode getGroovyData() {
        /**
         * getForObject
         *
         * 参数1 要请求的地址的url  必填项
         * 参数2 响应数据的类型 是String 还是 Map等 必填项
         * 参数3 请求携带参数 选填
         *
         * getForObject 方法的返回值就是 被调用接口响应的数据
         */
        String result = restTemplate.getForObject("http://localhost:8080/todo/getAll", String.class);
        return new ResponseCode(200, "ok!", result);
    }

    @GetMapping("getGroovyByIdForData")
    @ResponseBody
    public ResponseCode getGroovyByIdForData(@RequestParam("id") Integer id) {
        String result = restTemplate.getForObject("http://localhost:8080/todo/getById?todoId={1}", String.class, id);
        return new ResponseCode(200, "ok!", result);
    }

    @GetMapping("getGroovyByIdForEntity")
    @ResponseBody
    public ResponseCode getGroovyByIdForEntity(@RequestParam("id") Integer id) {
        /**
         * getForEntity 方法
         * 参数1 要请求的地址的url  必填项
         * 参数2 响应数据的类型 是String 还是 Map等 必填项
         * 参数3 请求携带参数 选填
         *
         * 返回值类型为 ResponseEntity
         *
         * 可以通过ResponseEntity 获取响应的数据,响应的状态码等信息
         */
        ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/todo/getById?todoId=" + id, String.class);
        return new ResponseCode(response.getStatusCodeValue(), response.getBody());
    }

    @GetMapping("getGroovyByIdForMap")
    @ResponseBody
    public ResponseCode getGroovyByIdForMap(@RequestParam("id") Integer id) {
        Map<String, Integer> map = new HashMap<>();
        map.put("todoId", id);

        String result = restTemplate.getForObject("http://localhost:8080/todo/getById?todoId={todoId}", String.class, map);
        return new ResponseCode(200, "ok!", result);
    }

    @PostMapping(value = "saveGroovyForObject")
    public ResponseCode saveGroovyForObject(@RequestBody JSONObject jsonObject) {
        /**
         * postForObject 返回值为响应的数据
         * 参数1 要请求地址的url
         * 参数2 通过LinkedMultiValueMap对象封装请求参数  模拟表单参数,封装在请求体中
         * 参数3 响应数据的类型
         */
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);
//        LinkedMultiValueMap<String, Object> request = new LinkedMultiValueMap<>();
//        request.set("task", task);
//        request.set("isCompleted", isCompleted);
        String result = restTemplate.postForObject("http://localhost:8080/todo/save", request, String.class);
        return new ResponseCode(200, "ok!", result);
    }

    @PostMapping("saveGroovyForLocation")
    public ResponseCode saveGroovyForLocation(@RequestBody JSONObject jsonObject){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);

        /**
         * postForLocation 这个API和前两个都不一样
         *
         * 登录or注册都是post请求,而这些操作完成之后呢?大部分都是跳转到别的页面去了,这种场景下,就可以使用 postForLocation 了,提交数据,并获取返回的URI
         * 响应参数要跳转的地址
         */
        URI uri = restTemplate.postForLocation("http://localhost:8080/todo/save", request);
        System.out.println(uri);
        return new ResponseCode(200,uri);
    }

    @PutMapping("updateGroovyExchange")
    public ResponseCode updateGroovyExchange(@RequestBody JSONObject jsonObject){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), headers);
        ResponseEntity<String> result = restTemplate.exchange("http://localhost:8080/todo/update", HttpMethod.PUT, request, String.class);
        return new ResponseCode(200,"ok!",result);
    }

    @DeleteMapping("deleteGroovy")
    public ResponseCode deleteGroovy(@RequestParam("id") Integer id){
        restTemplate.delete("http://localhost:8080/todo/del?todoId={todoId}",id);
        return new ResponseCode(200,"ok!");
    }
}

2.7 测试

2.7.1 getGroovyData方法

img

2.7.2 getGroovyByIdForData方法

img

2.7.3 getGroovyByIdForEntity方法

img

2.7.4 getGroovyByIdForMap方法

img

2.7.5 saveGroovyForObject方法

img

2.7.6 saveGroovyForLocation方法

img
img

2.7.7 updateGroovyExchange方法

img
img

2.7.8 deleteGroovy方法

img
img

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hikktn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值