Spring RestTemplate - 消费分页响应API java教程

403 阅读2分钟

Spring中的RestTemplate用于消费REST API,简化了流程。 它包括HTTP连接处理,并与Jackson绑定器集成,将Java对象序列化和反序列化为/从json对象。

它很容易在Java和Android代码库中集成外部API。

本教程将不涉及在Java中创建REST API。

RESTtemplate消耗普通的json数据

让我们假设REST API返回以下json数据。

下面的数据只返回一个数组,但没有分页数据。

[{"id":1,"mobile":"1234","email":test@gmail,"designation":"Manager","department":"Finance "}]

让我们创建一个java值对象类来存储来自REST API的数据。

public class EmployeeInfo {
    private String id;
    private String mobile;
    private String designation;
    private String department;
    private String email;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

并用REST API消耗一个计划。

final String url = "REST API URL";
RestTemplate restTemplate = new RestTemplate();
EmployeeInfo emp = restTemplate.getForObject(url, EmployeeInfo.class);

restTemplate 在Spring框架中的对象做了以下事情

  • 它为URL创建并管理一个HTTP连接管理器
  • 它使用Jackson库来序列化和反序列化来自JSOn数据的java对象
  • getForObject 接受URL和Object类,并返回java对象中的响应。

这就是Resttemplate如何简化从JSON转换的java对象的方式。

如何在spring中用resttemplate消费分页的响应

分页是一种逻辑,当有更多的记录时,会返回少数记录

假设,如果API返回以下的JSOn响应。

{"content":[{"id":1,"mobile":"1234","email":test@gmail,"designation":"Manager","department":"Finance "}],"last":true,"totalElements":1,"totalPages":1,"sort":[],"numberOfElements":1,"first":true,"size":20,"number":0,"empty":false}

API返回的可分页数据具有以下属性

  • content属性持有从API返回的实际数据
  • last true 表示最后一页
  • size 在一次调用中要返回的记录数
  • totalPages - 返回所有记录的总页数
  • sort - 在任何属性上都会给予排序。
  • first - 第一页或不是

如果API返回这些json数据,我们必须定制来处理这个可翻页的响应。

首先,让我们创建PaginatedResponse.java ,它扩展了spring框架的PageImpl


import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;

public class PaginatedResponse<T> extends PageImpl<T> {
    @JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
    public PaginatedResponse(@JsonProperty("content") List<T> content,
                            @JsonProperty("number") int number,
                            @JsonProperty("size") int size,
                            @JsonProperty("totalElements") Long totalElements,
                            @JsonProperty("pageable") JsonNode pageable,
                            @JsonProperty("last") boolean last,
                            @JsonProperty("totalPages") int totalPages,
                            @JsonProperty("sort") JsonNode sort,
                            @JsonProperty("first") boolean first,
                            @JsonProperty("first") boolean first,
                            @JsonProperty("empty") boolean empty) {

        super(content, PageRequest.of(number, size), totalElements);
    }

    public PaginatedResponse(List<T> content, Pageable pageable, long total) {
        super(content, pageable, total);
    }

    public PaginatedResponse(List<T> content) {
        super(content);
    }

    public PaginatedResponse() {
        super(new ArrayList<>());
    }
}

在消费API时,代码如下

我们必须使用ParameterizedTypeReference ,它提供了对jackson对象包装器的类型引用,以将PaginatedResponse转换为Employee类的格式。

ParameterizedTypeReference<PaginatedResponse<Employee>> responseType = new ParameterizedTypeReference<PaginatedResponse<Employee>>() { };

ResponseEntity<RestResponsePage<Employee>> result = restTemplate.exchange(url, HttpMethod.GET, null/, responseType);

List<Employee> employeeList = result.getBody().getContent();

结论

使用plan对象消费REST API是很简单的,但是分页响应的格式需要和spring类配合才能返回正确的格式。

由于任何原因,如果返回的响应与上述格式不同,你必须做相应的修改。