Rest Template 使用

大家好我是苏麟 今天带来Rest Template .

spring框架中可以用restTemplate来发送http连接请求, 优点就是方便.

Rest Template 使用

Rest Template 使用步骤

java 复制代码
    /**
     * RestTemple:
     * 1.创建RestTemple类并交给IOC容器管理
     * 2. 发送http请求的类
     */

1.注册RestTemplate对象

java 复制代码
@SpringBootApplication
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }


    /**
     * 创建RestTemple类并交给IOC容器管理
     *
     * @RestTemple 是发送http请求的类
     *
     * @LoadBalanced 负载均衡注解
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

2.发送HTTP请求

java 复制代码
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    //引入
    @Autowired
    private RestTemplate restTemplate;


    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);

        //2.利用RestTemplate发起http请求,查询用户信息
        //2.1 url
        String url = "http://userserver/user/" + order.getUserId();

        //2.2 发送http请求,实现远程调用
        User u = restTemplate.getForObject(url, User.class);

        //3.封装到order里
        order.setUser(u);

        // 4.返回
        return order;
    }
}

主要代码就是

java 复制代码
        //2.利用RestTemplate发起http请求,查询用户信息
        //2.1 url
        String url = "http://userserver/user/" + order.getUserId();

        //2.2 发送http请求,实现远程调用
        restTemplate.getForObject(url, User.class);

发送Get请求用 getForObject

参数: 第一个参数: 发送请求的路径 , 第二个参数 : 返回的类型

发送Post请求 postForObject

参数: 第一个参数: 发送请求的路径 , 第二个参数 : 请求数据对象 , 第三个参数 : 返回的类型

这期就到这里下期见!

相关推荐
phltxy5 小时前
C语言操作符详解
java·c语言·算法
步行cgn6 小时前
@Configuration 详解:Spring 配置类的核心注解
java·后端·spring
sunshine22 girl6 小时前
Java学习一 环境配置2 安装和基本使用Idea
java·学习·intellij-idea
嘿嘿-667 小时前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
策案案案9 小时前
YOLO: 将AI Agents嵌入到IntelliJ IDEA
java·大数据·人工智能·笔记·yolo·microsoft·intellij-idea
辰烨chenye10 小时前
LeetCode Hot 100 题解 · 堆篇
java·算法·leetcode
shehuiyuelaiyuehao10 小时前
算法29,前缀和,除自身以外的数组的乘积
java·数据结构·算法
小刘在重生~11 小时前
Java常用类|String类详解 + BigDecimal精准计算(含面试题)
java·开发语言·python
随遇而安zx11 小时前
【多线程】---JMM 与 volatile 深度解析
java·多线程