How to send array with Spring RestTemplate?

how to pass list<string> in get method using spring mvc
resttemplate post list of objects
resttemplate query param array
pass array to rest api java
parameterizedtypereference
resttemplate patchforobject
resttemplate getforobject list
resttemplate exchange get example with parameters

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.


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.

Get and Post Lists of Objects with RestTemplate, Learn how to use Spring's RestTemplate to send requests with JSON content. getForObject() to GET an array of objects via the responseType� Here, we'll try to send POST requests to the Person API by using the POST methods provided by the RestTemplate: postForObject, postForEntity, and postForLocation. Before we start to implement our unit tests, let's define a setup method to initialize the objects that we'll use in all our unit test methods:


I ended up constructing the URL by looping through the collection.

Map<String, Object> map = new HashMap<String, Object>();
map.put("category", parameters.getName());

String url = "http://localhost:8080/admin/train?category={category}";
if (positiveDocs != null && positiveDocs.size() > 0) {
    for (String id : positiveDocs) {
        url += "&positiveDocId[]=" + id;
    }
}
if (negativeDocId != null && negativeDocId.size() > 0) {
    for (String id : negativeDocId) {
        url += "&negativeDocId[]=" + id;
    }
}

TrainResponse response = restTemplate.getForObject(url, TrainResponse.class, map);

Spring Rest Template to send JsonArray - spring - html, I am using spring rest template to send json array as request. Source code to send request is as follow: JSONArray jsonArray = new JSONArray(); for (Iterator� In this Spring Boot RestTemplate POST request test example, we will create a POST API and then test it by sending request body along with request headers using postForEntity() method. 1. Maven dependencies


Try this

Change your request mapping from

@RequestMapping(value = "/train", method = RequestMethod.GET)

to

 @RequestMapping(value = "/train/{category}/{positiveDocId[]}/{negativeDocId[]}", method = RequestMethod.GET)

and your URL in restTemplate

change URl in the below given format

http://localhost:8080/admin/train/category/1,2,3,4,5/6,7,8,9

How to pass array as PathVariable in spring rest template?, How to pass array as PathVariable in spring rest template? ShilpaKulkarni. Asked on July 11, 2018. Hello,. I want to pass array as path parameter in URL. After learning to build Spring REST based RESTFul APIs for XML representation and JSON representation, let’s build a RESTFul client to consume APIs which we have written. Accessing a third-party REST service inside a Spring application revolves around the use of the Spring RestTemplate class. The RestTemplate class is designed on the same principles as the many other Spring *Template classes


Here's how I've achieved it:

The REST Controller:

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

The request:

List<String> skus = Arrays.asList("123","456","789");

Map<String, String> 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<String> skus) {
    return skus.stream().collect(Collectors.joining(","));
}

java Spring RestTemplate: sending array list of String in GET , @Ralph You are right. I updated the answer and removed the part talking about PathVariables. I strongly believe that this is wrong. articleids is part of the query� 1. RestTemplate Introduction. In today’s blog post we will have a look at Springs well-known rest client – the RestTemplate.The RestTemplate is the central class within the Spring framework for executing synchronous HTTP requests on the client side.


2. RestTemplate Module, Spring's RestTemplate is a robust, popular Java-based REST client. The Spring RestTemplate supports sending and receiving data encoded with gzip compression. that can read and write byte arrays from the HTTP request and response. In this article, you will learn how to make different kinds of HTTP POST requests by using the RestTemplate class in a Spring Boot application.. An HTTP POST request is used to create a new resource.


Spring RestTemplate Tutorial, In this tutorial you will learn how to use RestTemplate to send different Web Service Endpoint which returns a JSON Array of JSON Objects. This quick tutorial focuses on how to upload a multipart file using Spring’s RestTemplate. We'll see both a single file and multiple files – upload using the RestTemplate. 2.


Using RestTemplate in Spring, In today's blog post we will have a look at Springs well-known rest client – the HttpURLConnection from the Java SDK is used in RestTemplate . The ResponseEntity is typed to an array of Employee since we expect an� spring-webmvc 5.0.2.RELEASE: Spring Web MVC. javax.servlet-api 3.0.1 Java Servlet API; commons-fileupload 1.3.2: The Apache Commons FileUpload component provides a simple yet flexible means of adding support for multipart file upload functionality to servlets and web applications. JDK 1.8; Maven 3.3.9