栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

文章目录
  • 参考视频
  • 1.RestTemplate类概述
  • 2.RestTemplate方法
  • 3.RestTemplate使用示例 - 远程调用服务

参考视频

day1-12-RestTemplate调用远程服务

1.RestTemplate类概述

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

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

RestTemplate 用法详解

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

[GET]

[POST]

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

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

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

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

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/970124.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号