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

简介: 本文目录1. 背景2. 编写测试类

1. 背景

访问HTTP接口,应该是一种非常常见的工作了,Spring封装了RestTemplate,可以用来访问Rest web接口。


本篇我们演示下RestTemplate的使用。


2. 编写测试类

代码如下,可以看到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);
  }
}
相关文章
|
2天前
|
Java 开发者 Spring
Spring项目中Ordered接口的应用:全局过滤器(GlobalFilter)的顺序控制
Spring项目中Ordered接口的应用:全局过滤器(GlobalFilter)的顺序控制
10 2
|
2天前
|
Dubbo Java 应用服务中间件
Spring Boot 调用 Dubbo 接口与编写 Dubbo 接口实战
Spring Boot 调用 Dubbo 接口与编写 Dubbo 接口实战
10 1
|
3天前
|
Java Spring
|
2天前
|
JSON Java API
使用Spring Boot实现RESTful API
使用Spring Boot实现RESTful API
|
2天前
|
存储 API
什么是RESTful接口风格
什么是RESTful接口风格
7 0
|
3天前
|
JSON Java API
使用Spring Boot实现RESTful API
使用Spring Boot实现RESTful API
|
3天前
|
Java 机器人 程序员
Spring Boot中的RESTful API版本控制
Spring Boot中的RESTful API版本控制
|
3天前
使用Jetty编写RESTful接口
使用Jetty编写RESTful接口
6 0
|
6天前
|
Java
springboot自定义拦截器,校验token
springboot自定义拦截器,校验token
20 6