为了账号安全,请及时绑定邮箱和手机立即绑定

Spring之路(27)–使用RestTemplate访问Restful接口

标签:
Spring

背景

访问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);
	}

}

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
软件工程师
手记
粉丝
1.5万
获赞与收藏
1523

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消