参考视频
1.RestTemplate类概述
该类中拥有多个发送Http请求的方法。使用的步骤如下:
- 在SpringBoot启动类中创建Bean,并将这个Bean添加到Spring容器中;
- 在需要发送Http请求的类中,使用@Resource获取RestTemplate对象,并调用其中的方法发送请求。
2.RestTemplate方法
参数列表中的Class<T>用于指定返回值类型。
[GET]
[POST]
3.RestTemplate使用示例 - 远程调用服务
-
[服务准备] 在远程服务器(82.157.xx.xxx)的8081端口部署项目 test_resttemplate_02 ,有接口"/test/sayHello";
-
[创建调用者服务] 编写项目 test_resttemplate_01 ,设计接口"/test/sayHelloByRestTemplate",作用是访问远程服务器中test_resttemplate_01 的 "/test/sayHello"接口;
-
[实现接口功能] 实现 通过http请求访问远程服务器 的功能:
-
在SpringBoot启动类中创建RestTemplate对象,并将对象加入到Spring容器中成为Bean;
-
在接口类中,通过
@Resource
获取Bean; -
在接口类对应的方法中,使用restTemplate对象的
getForObject
方法向远程服务器发起Http请求,设置返回值类型为String;
-
-
[测试接口] 接口实现后,在本地启动 test_resttemplate_01 项目(端口号为8080),在浏览器中输入"http://localhost:8080/test/sayHelloByRestTemplate"访问接口。