Spring之路(27)–使用RestTemplate访问Restful接口
2020/2/10 8:24:31
本文主要是介绍Spring之路(27)–使用RestTemplate访问Restful接口,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
背景
访问HTTP接口,应该是一种非常常见的工作了,Spring封装了RestTemplate,可以用来访问Rest web接口。
本篇我们演示下RestTemplate的使用。
编写测试类
代码如下,可以看到RestTemplate的封装,可以说相当的简洁明了,似乎也没有必要做详细的解释,想必大家看到示例,就知道如何使用了。
此处想说的是相比于HttpClient等Http组件,这个简单多了。
package org.maoge.restfulblog; import java.util.List; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class BlogRestfulTest { /** * 测试入口 */ public static void main(String[] args) { BlogDo blog = new BlogDo(); blog.setAuthor("猫哥"); blog.setTitle("测试博客"); blog.setContent("非常完美吭"); testAddBlog(blog); testViewBlogs(); blog.setId(3L); blog.setContent("非常完美吭++"); testEditBlog(blog); testDeleteBlog(1L); } /** * 测试新增 */ public static void testAddBlog(BlogDo blog) { RestTemplate template = new RestTemplate(); ResponseEntity<Void> result = template.postForEntity("http://127.0.0.1:8080/restfulblog/blog", blog, Void.class); } /** * 测试获取博客列表 */ public static void testViewBlogs() { // 定义template对象 RestTemplate template = new RestTemplate(); // 发起get访问 ResponseEntity<List> result = template.getForEntity("http://127.0.0.1:8080/restfulblog/blog", List.class); System.out.println(result.getBody().size()); } /** * 测试修改 */ public static void testEditBlog(BlogDo blog) { RestTemplate template = new RestTemplate(); template.put("http://127.0.0.1:8080/restfulblog/blog/"+blog.getId(), blog); } /** * 测试删除 */ public static void testDeleteBlog(Long id) { RestTemplate template = new RestTemplate(); template.delete("http://127.0.0.1:8080/restfulblog/blog/"+id); } }
点击查看更多内容
这篇关于Spring之路(27)–使用RestTemplate访问Restful接口的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?
- 2024-05-09企业src漏洞挖掘-有意思的命令执行
- 2024-05-08阿里云域名注册流程,分享给第一次购买域名的新手站长!