spring rest client,如何在客户端请求中序列化对象

时间:2014-11-25 09:36:32

标签: spring-mvc java-ee resttemplate rest-client

在客户端我有

RestTemplate restTemplate = new RestTemplate();
Result r = restTemplate.getForObject("http://localhost:8080/test?key1=value1",Result.class);

我不想手动将“key1 = value1”附加到网址,是否可以拥有类似

的类
class Dto {
  private String key1;
  public void setKey1(String key1) {this.key1=key1}

并有弹簧自动序列化dto对象,因此调用就像

Result r = restTemplate.getForObject("http://localhost:8080/test", Result.class, dto);

在restTemplate中有这样的方法,但我不能让它工作,在服务器端我收到空对象。 我想我在DTO上遗漏了一些注释。 在服务器上我有

@RequestMapping(value = "/test")
@ResponseBody
public DTO test(DTO p) {
    p.setName("received");
    return p;
}

请指教。

1 个答案:

答案 0 :(得分:0)

考虑到您将所有端点保持为文件中的常量,您应该在url中使用占位符。在您的情况下,一个URL端点为http://localhost:8080/test?key1={0}&anotherParam={1},而您执行

restTemplate.getForObject("http://localhost:8080/test", Result.class, "keyVal","anotherKeyVal");

由于上一个参数的类型为varArgs,因此它将采用您想要发送的多个值,但顺序与您在种子URL中定义键的顺序相同。将它们放在那里的持有者由API本身负责。 的 [更新] 查看您的服务器端代码,您似乎希望在DTO对象中接收您的值。为此,您需要使用messageConverter(JSON或XML)POST(并使端点作为POST)数据。这样你的对象就会被你的messageConverter编组和解组。