Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Springboot rest模板获取有限行_Java - Fatal编程技术网

Java Springboot rest模板获取有限行

Java Springboot rest模板获取有限行,java,Java,我正在开发一个后端服务,它使用SpringBootREST模板查询外部服务,并显示响应。我想对返回的结果设置一些条件。响应是一个列表,如果可用记录少于3条,我希望返回0个结果。如果有3条或更多,那么我想返回3条记录。我如何做到这一点?任何提示都会非常有用。控制响应的最佳方法是使用拦截器。您可以在响应返回到客户端之前更新响应 RestTemplate restTemplate = new RestTemplate(); List<ClientHttpRequestInter

我正在开发一个后端服务,它使用SpringBootREST模板查询外部服务,并显示响应。我想对返回的结果设置一些条件。响应是一个列表,如果可用记录少于3条,我希望返回0个结果。如果有3条或更多,那么我想返回3条记录。我如何做到这一点?任何提示都会非常有用。

控制响应的最佳方法是使用
拦截器。您可以在响应返回到客户端之前更新响应

RestTemplate restTemplate = new RestTemplate();

        List<ClientHttpRequestInterceptor> interceptors
          = restTemplate.getInterceptors();
        if (CollectionUtils.isEmpty(interceptors)) {
            interceptors = new ArrayList<>();
        }
        interceptors.add(new MyRestTemplateInterceptor());
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
“rest模板”将返回ResponseEntity(org.springframework.http)

让我们假设这个反应是这样的

[
  {
    "idGear": "1",
    "name": "lala"
  }, {
    "idGear": "2",
    "name": "lala2"
  }
]
创建Java pojo类:

        @JsonInclude(JsonInclude.Include.NON_NULL)
        @JsonIgnoreProperties(ignoreUnknown = true)
        class Product {
        String idGear;
        String name;
        //Add Getter, Setters, Contructors 
        }
现在,将响应提取到数组中

ResponseEntity<Product[]> response =
  restTemplate.getForEntity("<URL>",Product[].class);
Product[] productResponse = response.getBody();
ResponseEntity<Product[]> response =
  restTemplate.getForEntity("<URL>",Product[].class);
Product[] productResponse = response.getBody();
Product[] products = null;
if(null != productResponse && productResponse.length > 3){
  products = new Product[]{productResponse[0], productResponse[1], productResponse[2]};
}else {
 products = new Product[]{};
}
return products;