Reputation: 3750
Hi what i trying to achieve is i want to consume other API and put some response data into List in my function using RestTemplate, here is how my code look like :
@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);
}
as you can see i try to get the response in to List, which is i try here restTemplate.postForObject(url, requestPartnerShipmentDto, new ParameterizedTypeReference<List<PartnerShipmentDto>>() {});
but i got error underlined in restTemplate.postForObject that look like this :
The method postForObject(String, Object, Class, Object...) in the type RestTemplate is not applicable for the arguments (String, HttpEntity, new ParameterizedTypeReference<List>(){})
What should i change to fix this?
Upvotes: 1
Views: 5578
Reputation: 1108
I tried the above but it did not work for me. This works nicely in Kotlin:
val uri = "http://localhost:$port/api/xxx/dosomething/"
log.info("URL for Controller was: [$uri]")
val result: ResponseEntity<Array<BillingOrder>>
= restTemplate!!.postForEntity(uri, ids, Array<BillingOrder>::class.java)
assertNotNull(result)
assertEquals(200, result.statusCodeValue)
val body = result.body
if (body != null) {
body.forEach { order ->
assertEquals("Success", order.billingState)
} else {
fail("Response body is null!")
}
On a tangent, if you have a post that does NOT return a value but takes params, here is that one:
uri = "http://localhost:$port/api/xxx/doSomething/${subscription.id}/"
log.info("URL for Controller was: [$uri]")
val x = restTemplate.postForEntity(uri, null, Void::class.java)
assertNotNull(x)
assertEquals(HttpStatus.SC_OK, x.statusCodeValue)
Upvotes: 0
Reputation: 375
If you want to use ParameterizedTypeReference<T>
, you need to use RestTemplate.exchange()
, since this is the only Method that exposes a parameter of type ParameterizedTypeReference<T>
.
List<PartnerShipmentDto> partnerShipmentDto = restTemplate.exchange(url,
HttpMethod.GET,
requestPartnerShipmentDto,
new ParameterizedTypeReference<List<PartnerShipmentDto>>() {})
.getBody();
Upvotes: 3