如何使用Spring的RestTemplate发布字符串数组 [英] How to use Spring`s RestTemplate to POST an array of strings

查看:171
本文介绍了如何使用Spring的RestTemplate发布字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用spring的restTemplate发布一个简单的字符串数组.有人成功了吗?

I am trying to post a simple array of strings using the spring`s restTemplate. Did anyone succeed with that ?

客户:

    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);
}

服务是:

    @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);
}

我收到了400个错误的请求.

I got 400 Bad Request.

我在做什么错了?

我正在使用默认的messageConverters.

I am using the default messageConverters.

我是否需要为简单的String数组实现自定义messageConverter?

Do I need to implement custom messageConverter for a simple array of Strings ?

推荐答案

以下是解决方法:

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); 
}

这篇关于如何使用Spring的RestTemplate发布字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆