Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate Send List an get List

I want to make a service with Spring's RestTemplate, in my service side the code is like this :

@PostMapping(path="/savePersonList")
@ResponseBody
public List<Person> generatePersonList(@RequestBody List<Person> person){
    return iPersonRestService.generatePersonList(person);
}

In client side if I call the service with this code:

List<Person> p = (List<Person>) restTemplate.postForObject(url, PersonList, List.class);

I can't use the p object as List<Person>, it will become a LinkedHashList. After some research I find a solution that said I have to call the service with exchange method:

ResponseEntity<List<Person>> rateResponse = restTemplate.exchange(url, HttpMethod.POST, personListResult, new ParameterizedTypeReference<List<Person>>() {});

and with this solution the server can't take the object and raise an exception , what's the correct way?

like image 583
Mohammad Mirzaeyan Avatar asked Oct 17 '16 05:10

Mohammad Mirzaeyan


People also ask

Is RestTemplate getting deprecated?

RestTemplate will still be used. But in some cases, the non-blocking approach uses much fewer system resources compared to the blocking one.

What is difference between getForObject and getForEntity in RestTemplate?

For example, the method getForObject() will perform a GET and return an object. getForEntity() : executes a GET request and returns an object of ResponseEntity class that contains both the status code and the resource as an object. getForObject() : similar to getForEntity() , but returns the resource directly.

What is the correct way of calling a REST API using RestTemplate that returns a list of long values?

correct way is , @Autowired RestTemplate class and use that Instead of create new object every time..


1 Answers

Check if your code is like below. This should work.

//header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//person list
List<Person> personList = new ArrayList<Person>();
Person person = new Person();
person.setName("UserOne");  
personList.add(person);
//httpEnitity       
HttpEntity<Object> requestEntity = new HttpEntity<Object>(personList,headers);
ResponseEntity<List<Person>> rateResponse = restTemplate.exchange(url, HttpMethod.POST, requestEntity,new ParameterizedTypeReference<List<Person>>() {});
like image 72
abaghel Avatar answered Oct 16 '22 07:10

abaghel