Reputation: 91
I am trying to post a simple array of strings using the spring`s restTemplate. Did anyone succeed with that ?
The client:
public void save(){
String company = "12345";
String productId = "10";
String[] colors = {"A","B","C","D","E"};
String convertUrl = "http://localhost:8080/cool-web/save";
MultiValueMap<String, Object> convertVars = new LinkedMultiValueMap<String, Object>();
convertVars.add("companyID", StringUtils.trimToEmpty(company));
convertVars.add("productId", StringUtils.trimToEmpty(productId));
convertVars.add("disclaimer", StringUtils.trimToEmpty("ffs"));
convertVars.add("colorsArray", colors);
restTemplate.postForObject(convertUrl, null, String.class, convertVars);
}
The Service is:
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void save(@RequestParam("colorsArray[]") String[] colors,
@RequestParam("disclaimer") String disclaimer,
@RequestParam("companyID") String companyID,
@RequestParam("productId") String productId) {
resourceService.save(colors, disclaimer, companyID, productId);
}
I got 400 Bad Request.
What am I doing wrong ?
I am using the default messageConverters.
Do I need to implement custom messageConverter for a simple array of Strings ?
Upvotes: 3
Views: 5922
Reputation: 91
Here is the solution:
public void save(){
String company = "12345";
String productId = "10";
String[] colors = {"A","B","C","D","E"};
String convertUrl = "http://localhost:8080/cool-web/save";
MultiValueMap<String, Object> convertVars = new LinkedMultiValueMap<String, Object>();
convertVars.add("companyID", StringUtils.trimToEmpty(company));
convertVars.add("productId", StringUtils.trimToEmpty(productId));
convertVars.add("disclaimer", StringUtils.trimToEmpty("ffs"));
for(String color:colors){
convertVars.add("colorsArray[]", color);
}
restTemplate.postForObject(convertUrl, convertVars , String.class);
}
Upvotes: 6
Reputation: 448
@RequestParam(value)
value - "The name of the request parameter to bind to." So @RequestParam("colorsArray[]") String[] colors
trying to find param with name "colorsArray[]" but u put parameter with name "colorsArray". May be that is the reason.
Upvotes: 0
Reputation: 6079
If you are trying POST MultiValueMap
, use Map.class
instead of String.class
in the code:
restTemplate.postForObject(convertUrl, null, Map.class, convertVars);
And your service method is wrong I guess. Because you are posting MultiValueMap
and in save
method you are trying to get all the internal variables as method parameters i.e. RequestParam.
That's not going to happen. You will have to accept only MultiValueMap
there and take things out of it for use.
public void save(@RequestParam("colorsArray[]") MultiValueMap<String, Object> convertVars ) {
resourceService.save(convertVars.getColors(), .... );
}
Upvotes: 1