How to send array with Spring RestTemplate?

后端 未结 4 780
心在旅途
心在旅途 2021-01-14 06:43

How do I send array parameter with Spring RestTemplate?

This is the server side implementation:

@RequestMapping(value = \"/train\", method = RequestM         


        
4条回答
  •  旧时难觅i
    2021-01-14 07:35

    Here's how I've achieved it:

    The REST Controller:

    @ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public ResponseEntity getPublicationSkus(
           @RequestParam(value = "skus[]", required = true) List skus) {
        ...
    }
    

    The request:

    List skus = Arrays.asList("123","456","789");
    
    Map params = new HashMap<>();
    params.put("skus", toPlainString(skus));
    
    Response response = restTemplate.getForObject("http://localhost:8080/test?skus[]={skus}", 
                                          Response.class, params);
    

    Then you just need to implement a method that converts the List or the String[] to a plain string separated by commas, for example in Java 8 would be something like this:

    private static String toPlainString(List skus) {
        return skus.stream().collect(Collectors.joining(","));
    }
    

提交回复
热议问题