SpringCloud | 01.使用RestTemplate实现远程服务的调用

参考视频

day1-12-RestTemplate调用远程服务

1.RestTemplate类概述

该类中拥有多个发送Http请求的方法。使用的步骤如下:

  • 在SpringBoot启动类中创建Bean,并将这个Bean添加到Spring容器中;
  • 在需要发送Http请求的类中,使用@Resource获取RestTemplate对象,并调用其中的方法发送请求。

2.RestTemplate方法

RestTemplate 用法详解

参数列表中的Class<T>用于指定返回值类型

[GET]

图片描述

[POST]

图片描述

3.RestTemplate使用示例 - 远程调用服务

  1. [服务准备] 在远程服务器(82.157.xx.xxx)的8081端口部署项目 test_resttemplate_02 ,有接口"/test/sayHello";

    image-20220613113830519

  2. [创建调用者服务] 编写项目 test_resttemplate_01 ,设计接口"/test/sayHelloByRestTemplate",作用是访问远程服务器中test_resttemplate_01 的 "/test/sayHello"接口;

    image-20220613114553635

  3. [实现接口功能] 实现 通过http请求访问远程服务器 的功能:

    • 在SpringBoot启动类中创建RestTemplate对象,并将对象加入到Spring容器中成为Bean;

      image-20220613114840423

    • 在接口类中,通过@Resource获取Bean;

      image-20220613115026434

    • 在接口类对应的方法中,使用restTemplate对象的getForObject方法向远程服务器发起Http请求,设置返回值类型为String;

      image-20220613115324775

  4. [测试接口] 接口实现后,在本地启动 test_resttemplate_01 项目(端口号为8080),在浏览器中输入"http://localhost:8080/test/sayHelloByRestTemplate"访问接口。

    image-20220613115528001

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值