How can you pass an array in a POST with Spring RestTemplate?

21,477

Solution 1

You can check this post: How to pass List or String array to getForObject with Spring RestTemplate, solution for that post is:

List or other type of objects can post with RestTemplate's postForObject method. My solution is like below:

controller:

@RequestMapping(value="/getLocationInformations", method=RequestMethod.POST)
@ResponseBody
public LocationInfoObject getLocationInformations(@RequestBody RequestObject requestObject)
{
    // code block
}

Create a request object for posting to service:

public class RequestObject implements Serializable
{
    public List<Point> pointList    = null;
}

public class Point 
{
    public Float latitude = null;
    public Float longitude = null;
}

Create a response object to get values from service:

public class ResponseObject implements Serializable
{
    public Boolean success                  = false;
    public Integer statusCode               = null;
    public String status                    = null;
    public LocationInfoObject locationInfo  = null;
}

Post point list with request object and get response object from service:

String apiUrl = "http://api.website.com/service/getLocationInformations";
RequestObject requestObject = new RequestObject();
// create pointList and add to requestObject
requestObject.setPointList(pointList);

RestTemplate restTemplate = new RestTemplate();
ResponseObject response = restTemplate.postForObject(apiUrl, requestObject, ResponseObject.class);

// response.getSuccess(), response.getStatusCode(), response.getStatus(), response.getLocationInfo() can be used

Solution 2

How to POST array:

private String doPOST(String[] array) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);
    }

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(
            builder.build().encode().toUri(),
            HttpMethod.POST,
            requestEntity,
            String.class);

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    }
    return result;
}

The POST request will have next structure:

POST https://my_url?array=your_value1&array=your_value2

On Server side:

public class MyServlet extends HttpServlet {
 @Override
    public void doPost(HttpServletRequest req, HttpServletResponse response) {

        try {
            String[] array = req.getParameterValues("array");
            String result = doStaff(array);
            response.getWriter().write(result);
            response.setStatus(HttpServletResponse.SC_ACCEPTED);

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}
Share:
21,477
Joe
Author by

Joe

Updated on July 09, 2022

Comments

  • Joe
    Joe almost 2 years

    I am having difficulty passing an array in a POST using Spring's RestTemplate. The following is my code that I am using:

    I am calling the RestTemplate here:

    private static void sendEntries() {
        RestTemplate restTemplate = new RestTemplate();
        String uri = "http://localhost:8080/api/log/list.json";
    
        // Both LogEntry and ExceptionEntry extend Entry
        LogEntry entry1 = new LogEntry();
        ExceptionException entry2 = new ExceptionEntry();
    
        Entry[] entries = {entry1, entry2};
    
        entries = restTemplate.postForObject(uri, entries, Entry[].class);
    
        System.out.println(new Gson().toJson(entries));
    }
    

    And the Controller contains:

    @RequestMapping(value = "api/log/list", method = RequestMethod.POST)
    public @ResponseBody Entry[] saveList(@RequestBody Entry[] entries) {
        for (Entry entry : entries) {
            entry = save(entry);
        }
    
        return entries;
    }
    

    This results in a:

    org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    

    It doesn't look like the array is being added to the request. All other POST request work when I am not trying to pass an array. I am just not sure what I need to do to get the array to pass over properly.

    Is this the proper way of doing it? Is it possible to pass a Collection instead?