如何使用Spring Boot RestTemplate

270 阅读3分钟

Spring Boot RestTemplate入门

消费RESTful网络服务需要大量的模板代码。创建Spring Boot REST模板是为了简化Spring Boot应用程序中的REST服务消费。

开始使用Spring Boot RestTemplate

在本教程中,我们将创建一个消费json占位符API的Spring Boot应用程序。

前提条件

  1. 在你的计算机上安装[JDK]。
  2. 一个IDE。我使用[Intelij IDEA]。
  3. 用于测试API调用的[PostMan]。

项目设置

我们将使用[spring initializr]来启动我们的应用程序。

  • 访问[spring initializr],输入项目名称为RestTemplate
  • 添加Spring WebLombok 作为项目依赖。
  • 点击生成项目按钮,下载项目模板代码的zip文件。
  • 解压缩文件,在你喜欢的IDE中打开未压缩的文件。

应用层

RestTemplateApplication.java 文件中更新代码片段,如下所示。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestTemplateApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestTemplateApplication.class, args);
    }

    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

在上面的代码片段中,我们将getRestTemplate() 函数作为Bean ,注入到我们的应用程序中。

领域层

在项目根目录下,创建一个名为domain 的新包。创建一个新的java类文件,名为Post ,并添加下面的代码片段。

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Post {
    @JsonProperty("userId")
    int userId;
    @JsonProperty("id")
    int id;
    @JsonProperty("title")
    String title;
    @JsonProperty("body")
    String body;
}
  • @AllArgsConstructor - 是一个Lombok注解,用于生成一个带有 类所有成员变量的构造函数。Post
  • @NoArgsConstructor - 是一个Lombok注解,为 类生成一个空的构造函数。Post
  • @Data - 注解为 的成员变量生成 和 。Post class getters setters

控制器层

  • 在项目根目录下,创建一个名为controllers 的包。
  • 在我们上面创建的controllers 目录中,创建一个名为RestConsumer 的java类,并添加下面的代码片断。
import com.example.resttemplate.domain.Post;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RestConsumer {
    RestTemplate restTemplate;

    public RestConsumer(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @RequestMapping(value = "/posts")
    public Post[] getProductList() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<>(httpHeaders);
        return restTemplate.exchange("https://jsonplaceholder.typicode.com/posts", HttpMethod.GET, entity, Post[].class).getBody();
    }

    @RequestMapping(value = "/posts/create")
    public String createPost(@RequestBody Post post) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<Post> entity = new HttpEntity<Post>(post, httpHeaders);
        return restTemplate.exchange("https://jsonplaceholder.typicode.com/posts", HttpMethod.POST, entity, String.class).getBody();

    }

    @RequestMapping(value = "/posts/update/{id}")
    public String updatePost(@PathVariable("id") int id, @RequestBody Post post) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<Post> entity = new HttpEntity<>(post, httpHeaders);
        return restTemplate.exchange("https://jsonplaceholder.typicode.com/posts/" + id, HttpMethod.PUT, entity, String.class).getBody();
    }

    @RequestMapping(value = "/posts/delete/{id}")
    public String deletePost(@PathVariable("id") int id) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<>(httpHeaders);
        return restTemplate.exchange("https://jsonplaceholder.typicode.com/posts/" + id, HttpMethod.DELETE, entity, String.class).getBody();
    }

}
  • @RestController - 标记 类为RestController。Spring Boot Rest控制器处理传入和传出的HTTP请求。RestConsumer
  • RestTemplate 是通过 类的构造函数注入的。Spring Boot 5.0及以后的版本鼓励构造器注入,而不是字段注入。RestController
  • @RequestMapping() - 添加可以访问该资源的路径。
  • getProductList() 函数从json占位符中获取所有的 。post
  • RestTemplate接收4个参数。
    1. URL - 我们可以访问该资源的端点。
    2. HTTP方法 - 用于访问资源的HTTP方法,即GET、POST、DELETE和PUT。
    3. Entity - HTTP实体,包含头信息和要发送的数据,即在POST和PUT请求中。
    4. 数据类 - 一个代表正在传输的数据的java类,即在我们的POST请求中,我们正在传输一个POST,而在我们的DELETE请求中,我们正在接收String作为响应。
  • httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); 设置要传输的数据类型为 。JSON

测试端点

GET请求

GET request

POST请求

POST request

PUT请求

PUT request

DELETE请求

DELETE request

总结

现在你已经学会了如何通过Spring Boot Rest模板消费RESTful Web服务,创建一个Spring Boot应用程序,通过REST端点暴露其服务,并从另一个Spring Boot应用程序消费端点。