【问题标题】:spring rest client, how to serialize object in client requestspring rest客户端,如何在客户端请求中序列化对象
【发布时间】:2023-04-09 21:55:01
【问题描述】:

在客户端我有

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

我不想手动将“key1=value1”附加到 url,是否可以有一个类似的类

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

并让 spring 自动序列化 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;
}

请指教。

【问题讨论】:

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


【解决方案1】:

考虑到您将所有端点作为一个常量保存在一个文件中,您应该在 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)数据。这样你的对象就会被你的 messageConverter 编组和解组。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-26
  • 2021-07-01
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 1970-01-01
  • 2012-02-15
相关资源
最近更新 更多