SpringCloud(3) ------>RestTemplate调用接口示例
RestTemplate是一个HTTP客户端,使用它我们可以方便的调用HTTP接口,支持GET、POST、PUT、DELETE等方法。
一、getForObject方法
1、通过RestTemplate发送Get请求
wordAppUrl为服务地址:例如http://word-app
word-app为服务名称
@GetMapping("/findAllWord") public CommonResult findAllWord(@RequestParam String userCode) { return restTemplate.getForObject(wordAppUrl + "/word/findWordByUserCode?userCode={1}", CommonResult.class, userCode); }
@GetMapping("/findWordById2") public CommonResult findWordById2(@RequestParam Integer id) { return restTemplate.getForObject(wordAppUrl + "/word/findById2?id={1}", CommonResult.class, id); }
2、通过RestTemplate发送Post请求
/** * 根据Id集合查询 * postForObject 测试 */ @GetMapping("/findWordByIds") public CommonResult findWordByIds() { Integer[] ids = {1,2,3}; return restTemplate.postForObject(wordAppUrl + "/word/findByIds",ids, CommonResult.class); }
/** * postForObject 测试 */ @GetMapping("/createWord") public CommonResult createWord() { Word word = Word.builder().id(101).chinese("自己").english("self").author("liangd").commitTime(new Date()).build(); return restTemplate.postForObject(wordAppUrl + "/word/create", JSONObject.toJSON(word), CommonResult.class); }
3、通过RestTemplate发送Put请求
/** * put 测试 */ @GetMapping("/updateWord") public CommonResult updateWord() { Word word = Word.builder().id(101).chinese("爱好").english("hobby").author("liangd").commitTime(new Date()).build(); restTemplate.put(wordAppUrl + "/word/update", JSONObject.toJSON(word),CommonResult.class); return CommonResult.success(null); }
4、通过RestTemplate发送Delete请求
/** * delete 测试 */ @GetMapping("/deleteWord") public CommonResult deleteWord() { Integer id = 101; restTemplate.delete(wordAppUrl + "/word/delete?id={1}", id); return CommonResult.success(null); }
二、getForEntity方法
返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等,
@GetMapping("/findWordById1/{id}") public CommonResult findWordById1(@PathVariable Integer id) { ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(wordAppUrl + "/word/findById1/{1}", CommonResult.class, id); System.out.println(forEntity); return forEntity.getBody(); }
三、配置RestTemplate
@Configuration public class RibbonConfig { /** * /使用@LoadBalanced注解赋予RestTemplate负载均衡的能力,默认是线性轮询的方式 */ @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }
分类:
SpringCloud
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix