Spring RestRemplate postforobject,请求参数具有整数值

时间:2013-12-09 19:33:07

标签: spring rest spring-mvc resttemplate

我在Spring休息服务中有一个方法。

@RequestMapping(value = "test/process", method = RequestMethod.POST)
public @ResponseBody MyResponse processRequest(String RequestId, int count)

我正在使用Spring RestTemplate这样调用此服务。

RestTemplate restTemplate = this.getRestTemplate();
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("RequestId", RequestId);
map.add("count", count); 
restTemplate.postForObject(url, map,MyResponse.class);

当我尝试调用客户端方法时,我得到了找不到合适的HttpMessageConverter请求类型[java.lang.Integer]

的异常
org.springframework.http.converter.HttpMessageNotWritableException: Could not write request: no suitable HttpMessageConverter found for request type [java.lang.Integer]
at org.springframework.http.converter.FormHttpMessageConverter.writePart(FormHttpMessageConverter.java:310)
at org.springframework.http.converter.FormHttpMessageConverter.writeParts(FormHttpMessageConverter.java:270)
at org.springframework.http.converter.FormHttpMessageConverter.writeMultipart(FormHttpMessageConverter.java:260)
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:200)
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:1)
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:596)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:444)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:409)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:287)

我知道其中一种方法是将所有参数作为String传递。但我可能需要稍后将复杂数据类型作为参数传递。 有什么方法可以实现这一目标。 我用谷歌搜索,一些选项似乎是编写我自己的转换器。我应该如何开始解决这个问题。

1 个答案:

答案 0 :(得分:6)

此错误的根本原因是,通过在Integer中指定LinkedMultiValueMapRestTemplate将认为您的请求是多部分请求。默认情况下,没有注册HttpMessageConverter可以处理将Integer类型的值写入请求正文。

正如您所说,您可以将count更改为String来处理这种情况。毕竟,HTTP请求参数中没有Integer类型。但是,你很担心

  

但我可能需要稍后将复杂数据类型作为参数传递。

假设这样的事情

public @ResponseBody MyResponse processRequest(String RequestId, int count, Complex complex) {

public class Complex {
    private String someValue;
    private int intValue;

    public String getSomeValue() {
        return someValue;
    }

    public void setSomeValue(String someValue) {
        this.someValue = someValue;
    }

    public int getIntValue() {
        return intValue;
    }

    public void setIntValue(int intValue) {
        this.intValue = intValue;
    }

    public String toString() {
        return someValue + " " + intValue;
    }
}

以下内容可以正常使用

MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("RequestId", "asd");
map.add("count", "42");
map.add("someValue", "complex");
map.add("intValue", "69");
restTemplate.postForObject(url, map,MyResponse.class);

请记住,请求参数用于按名称填充模型属性的字段。

更好的解决方案是让您使用像JSON或XML这样的序列化标准。

相关问题