【问题标题】:How to use RestTemplate to get result in List and put the response into List?如何使用 RestTemplate 在 List 中获取结果并将响应放入 List?
【发布时间】:2020-11-26 14:34:11
【问题描述】:

嗨,我想要实现的是我想使用其他 API 并使用 RestTemplate 将一些响应数据放入我的函数中的 List,这是我的代码的样子:

@PostMapping("/save-new")
public ResponseEntity<ShipmentAddressGrouping> saveNewShipmentAddressGrouping(@Valid @RequestBody InputRequest<ShipmentAddressGroupingDto> request) {
    String url = baseUrl + "/load-list";

    HttpEntity<PartnerShipmentDto> requestPartnerShipmentDto = new HttpEntity<>(new PartnerShipmentDto());
    RestTemplate restTemplate = new RestTemplate();
    List<PartnerShipmentDto> partnerShipmentDto = restTemplate.postForObject(url, requestPartnerShipmentDto, new ParameterizedTypeReference<List<PartnerShipmentDto>>() {});

    ShipmentAddressGrouping newShipmentAddressGrouping = shipmentAddressGroupingService.save(request);
    return ResponseEntity.ok(newShipmentAddressGrouping);

}

如您所见,我尝试在 List 中获取响应,我在这里尝试restTemplate.postForObject(url, requestPartnerShipmentDto, new ParameterizedTypeReference&lt;List&lt;PartnerShipmentDto&gt;&gt;() {});

但我在 restTemplate.postForObject 中得到如下下划线的错误:

方法 postForObject(String, Object, Class, Object...) 在 类型 RestTemplate 不适用于参数(字符串, HttpEntity,新 ParameterizedTypeReference(){})

我应该改变什么来解决这个问题?

【问题讨论】:

  • 我自己没有尝试过postForObject,但是从查看:docs.spring.io/spring-framework/docs/current/javadoc-api/org/… 看起来postForObject 的三进制for 需要第三个参数是responseType,所以List.class会在你的情况下工作,但你会收到关于泛型的警告。
  • 嗨@BillNaylor,它也对我有用,但是我收到了关于泛型的警告,我选择使用 Bernard 回答来使用交换而不是 postForObject,所以我也可以指定另一种方法,谢谢。我会找到 List.class 将来可以在哪里使用非常感谢你
  • 我认为为了避免泛型警告,您可以将List&lt;PartnerShipmentDto&gt; 封装在您自己的类中,然后引用它。

标签: java spring microservices resttemplate


【解决方案1】:

如果你想使用ParameterizedTypeReference&lt;T&gt;,你需要使用RestTemplate.exchange(),因为这是唯一暴露ParameterizedTypeReference&lt;T&gt;类型参数的方法。

List<PartnerShipmentDto> partnerShipmentDto = restTemplate.exchange(url, 
                HttpMethod.GET, 
                requestPartnerShipmentDto,
                new ParameterizedTypeReference<List<PartnerShipmentDto>>() {})
        .getBody();

【讨论】:

  • 我认为您不需要使用交换功能.. postForObject 也可以解决问题
猜你喜欢
  • 2018-06-27
  • 2021-03-27
  • 2013-04-29
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 2021-12-26
  • 1970-01-01
相关资源
最近更新 更多