Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send array with Spring RestTemplate?

Tags:

java

rest

spring

How do I send array parameter with Spring RestTemplate?

This is the server side implementation:

@RequestMapping(value = "/train", method = RequestMethod.GET)
@ResponseBody
public TrainResponse train(Locale locale, Model model, HttpServletRequest request, 
    @RequestParam String category,
    @RequestParam(required = false, value = "positiveDocId[]") String[] positiveDocId,
    @RequestParam(required = false, value = "negativeDocId[]") String[] negativeDocId) 
{
    ...
}

This is what I've tried:

Map<String, Object> map = new HashMap<String, Object>();
map.put("category", parameters.getName());
map.put("positiveDocId[]", positiveDocs); // positiveDocs is String array
map.put("negativeDocId[]", negativeDocs); // negativeDocs is String array
TrainResponse response = restTemplate.getForObject("http://localhost:8080/admin/train?category={category}&positiveDocId[]={positiveDocId[]}&negativeDocId[]={negativeDocId[]}", TrainResponse.class, map);

The following is the actual request URL which is obviously incorrect:

http://localhost:8080/admin/train?category=spam&positiveDocId%5B%5D=%5BLjava.lang.String;@4df2868&negativeDocId%5B%5D=%5BLjava.lang.String;@56d5c657`

Have been trying to search around but couldn't find a solution. Any pointers would be appreciated.

like image 937
Stanley Avatar asked Jun 15 '26 08:06

Stanley


1 Answers

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 https://www.rfc-editor.org/rfc/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.

like image 158
dschulten Avatar answered Jun 17 '26 20:06

dschulten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!