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接口的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程