02、RestTemplate学习笔记

简介: 02、RestTemplate学习笔记

一、RestTemplate


RestTemplate使用详解


RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。


之前的HTTP开发是用apache的HttpClient开发,代码复杂,还得操心资源回收等。代码很复杂,冗余代码多。


二、快速使用


SpringBoot依赖2.7.1版本:我们只需要导入web启动器即可


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>


我们来进行编写三种案例:①GET。②POST JSON。③POST 表单。


package com.changlu.resttemplate.controller;
import com.changlu.resttemplate.domain.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
 * @Description: 测试控制器
 * @Author: changlu
 * @Date: 4:04 PM
 */
@RestController
public class TestController {
    @GetMapping("/testGet")
    public String get(String name) {
        System.out.println(name);
        return "ok";
    }
    /**
     * post传参 两种
     *  json参数的核心  header content-type = application/json;charset=utf-8
     *
     * @return
     */
    @PostMapping("/testPost1")
    public String testPost1(@RequestBody User user) {
        System.out.println(user);
        return "ok";
    }
    /**
     * 接收表单参数
     * <form action=/testPost2
     * <input name=ccc value=ssss
     *  header content-type = application/x-www-form-urlencoded
     * @param user
     * @return
     */
    @PostMapping("/testPost2")
    public String testPost2(User user) {
        System.out.println(user);
        return "ok";
    }
}



接着我们来使用测试类RestTemplate来进行测试:分别对应三个请求


package com.changlu.resttemplate;
import com.changlu.resttemplate.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
@SpringBootTest
class RestTemplateApplicationTests {
    @Test
    void contextLoads() {
        RestTemplate restTemplate = new RestTemplate();
        //访问百度页面
        String url = "https://www.baidu.com";
        String content = restTemplate.getForObject(url, String.class);
        System.out.println(content);
    }
    @Test
    void testGet() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/testGet?name=cxs";
        //        String result = restTemplate.getForObject(url, String.class);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        // http:// 协议 (规范 接头暗号)
        // 请求头 请求参数 .. 响应头 响应状态码 报文 ....
        System.out.println(responseEntity);
    }
    @Test
    void testPostJson() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/testPost1";
        //封装对象
        User user = new User("changlu", 22, 1000D);
        //发送POST,而且是JSON参数,在web里面默认会使用jackson,会将对象转为字符串
        String content = restTemplate.postForObject(url, user, String.class);
        System.out.println(content);
    }
    @Test
    void testPost() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/testPost2";
        //对于表单参数,使用LinkedMultiValueMap来进行封装
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("name", "changlu");
        map.add("age", 26);
        map.add("price", 80080);
        String content = restTemplate.postForObject(url, map, String.class);
        System.out.println(content);
    }
}
相关文章
|
缓存 JavaScript 前端开发
|
JSON Java 数据安全/隐私保护
java中的http请求的封装(GET、POST、form表单、JSON形式、SIGN加密形式)
java中的http请求的封装(GET、POST、form表单、JSON形式、SIGN加密形式)
1333 1
|
消息中间件 Windows
win10 安装RabbitMQ的步骤--和报错解决
win10 安装RabbitMQ的步骤--和报错解决
613 4
|
JavaScript Java 关系型数据库
Spring事务失效的8种场景
本文总结了使用 @Transactional 注解时事务可能失效的几种情况,包括数据库引擎不支持事务、类未被 Spring 管理、方法非 public、自身调用、未配置事务管理器、设置为不支持事务、异常未抛出及异常类型不匹配等。针对这些情况,文章提供了相应的解决建议,帮助开发者排查和解决事务不生效的问题。
2616 1
|
Kubernetes 网络协议 druid
一文详解长连接黑洞重现和分析
本文先通过重现在不同业务线反复出现的问题,详细描述了从业务、数据库、OS等不同的角度来分析如何解决它。
|
数据库 开发者 Python
Python后端开发入门指南:从零开始,用Flask打造你的第一个Web应用!
【8月更文挑战第21天】Python凭借简洁的语法和丰富的库支持,在后端开发中备受青睐。本指南通过Flask框架介绍Python后端开发的基础步骤。首先安装Flask (`pip install flask`),接着创建应用实例及路由,如定义根路由`/`显示&quot;Hello, World!&quot;。为处理复杂逻辑如数据库操作,可使用Flask-SQLAlchemy扩展,安装后(`pip install flask-sqlalchemy`)配置数据库并定义模型。这些基本步骤为初学者提供了实用的起点,帮助快速上手Python后端开发。
1897 0
|
JSON Cloud Native Linux
gRPC-Gateway 快速实战
gRPC-Gateway 快速实战
387 0
gRPC-Gateway 快速实战
|
缓存 Java 数据库
第8章 Spring Security 的常见问题与解决方案(2024 最新版)(下)
第8章 Spring Security 的常见问题与解决方案(2024 最新版)
361 0
|
前端开发 Java 开发工具
【SpringBoot】文件分片上传、合并
【SpringBoot】文件分片上传、合并