Spring RestTemplate Send List an get List

▼魔方 西西 提交于 2019-12-01 22:57:45

问题


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?


回答1:


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>>() {});



回答2:


It may be helpful for you.

  List<Integer> officialIds = null;
  //add values to officialIds 
  RestTemplate restTemplate = new RestTemplate();

  HttpHeaders headers = new HttpHeaders();

  HttpEntity<List<Integer>> request = new HttpEntity<List<Integer>>(officialIds, 
    headers);

  ResponseEntity<YourResponseClass[]> responses = 
  restTemplate.postForEntity("your URL", request , YourResponseClass[].class );

  List<YourResponseClass> list = Arrays.asList(responses.getBody());


来源:https://stackoverflow.com/questions/40079053/spring-resttemplate-send-list-an-get-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!