How to send array with Spring RestTemplate?

后端 未结 4 753
心在旅途
心在旅途 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条回答
  •  终归单人心
    2021-01-14 07:44

    Spring's UriComponentsBuilder does the trick and allows also for Variable expansion. Assuming that you want to pass an array of strings as param "attr" to a resource for which you only have a URI with path variable:

    UriComponents comp = UriComponentsBuilder.fromHttpUrl(
        "http:/www.example.com/widgets/{widgetId}").queryParam("attr", "width", 
            "height").build();
    UriComponents expanded = comp.expand(12);
    assertEquals("http:/www.example.com/widgets/12?attr=width&attr=height", 
       expanded.toString());
    

    Otherwise, if you need to define a URI that is supposed to be expanded at runtime, and you do not know the size of the array in advance, use an http://tools.ietf.org/html/rfc6570 UriTemplate with {?key*} placeholder and expand it with the UriTemplate class from https://github.com/damnhandy/Handy-URI-Templates.

    UriTemplate template = UriTemplate.fromTemplate(
        "http://example.com/widgets/{widgetId}{?attr*}");
    template.set("attr", Arrays.asList(1, 2, 3));
    String expanded = template.expand();
    assertEquals("http://example.com/widgets/?attr=1&attr=2&attr=3", 
        expanded);
    

    For languages other than Java see https://code.google.com/p/uri-templates/wiki/Implementations.

提交回复
热议问题