Java Spring RestTemplate 发送列表和获取列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40079053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring RestTemplate Send List an get List
提问by Mohammad Mirzaeyan
I want to make a service with Spring's RestTemplate
, in my service side the code is like this :
我想用 Spring 做一个服务RestTemplate
,在我的服务端代码是这样的:
@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:
我不能将p
对象用作List<Person>
,它将成为LinkedHashList
. 经过一番研究,我找到了一个解决方案,说我必须使用交换方法调用服务:
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?
使用此解决方案,服务器无法接受对象并引发异常,正确的方法是什么?
回答by abaghel
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>>() {});
回答by Sourav Ghadai
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());