将JSON发送到端点并不起作用

时间:2018-04-22 14:39:21

标签: java spring rest resttemplate

想法:我想调用一个生成uploadPicture的方法。一旦准备就绪,我想将此列表重定向到给定的端点。

addCollection

ArrayList

class for generating the ArrayList

    @GetMapping("/createcustomer/{start}/{end}")
    @ResponseBody
    public ArrayList<Customer> createCustomer(@PathVariable int start, @PathVariable int end) {
        ArrayList<Customer> customerList = new ArrayList<Customer>();
        IntStream.range(start, end).parallel().forEach(index -> {
            customerList.add(generateCustomer());
        });

        RestTemplate restTemplate = new RestTemplate();
        String callbackURL = "http://localhost:8080/customerListEndpoint";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<?> entity = new HttpEntity<>(headers);
        restTemplate.exchange(callbackURL, HttpMethod.POST, entity, ArrayList.class);
        return customerList;
    }

endpoint for receiving the ArrayList

@PostMapping("/customerListEndpoint")
     public void createCustomer(@RequestBody ArrayList<Customer> arrayList) {
        for(int i=0; i<arrayList.size(); i++) {
            System.out.println(arrayList.get(i));
        }
     }

1 个答案:

答案 0 :(得分:2)

您可以像HTTP一样发送请求正文和HTTP实体中的标题

ObjectMapper mapper = new ObjectMapper();
String requestJson = mapper.writeValueAsString(customerList);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);