【问题标题】:How to POST data with Spring-boot RestTemplate如何使用 Spring-boot RestTemplate 发布数据
【发布时间】:2017-10-30 14:59:42
【问题描述】:

其实我有这个 Rest Template 请求:

@RequestMapping(value = "/uploadProperties", method = RequestMethod.POST)
public @ResponseBody RessourceMetadata uploadProperties(
        @RequestParam(value = "group", required = true) String group,
        @RequestParam(value = "id", required = true) String id,
        @RequestParam(value = "version", required = true) String version,
        @RequestParam(value = "env", required = true) String env) {
    try {
        Ressource ressource = new Ressource(content, group, id, version, env, PropertiesFileUtils.getPropertiesFilename());
        getRessourceService().save(ressource);
        return ressource.getMetadata();
    } catch (RuntimeException e) {
        log.error("Error while uploading.", e);
        throw e;
    } catch (Exception e) {
        log.error("Error while uploading.", e);
        throw new RuntimeException(e);
    }
}

我想像这样添加@RequestBody

    @RequestBody @RequestParam(value = "content", required = true) ????? content

这个新的content 可以包含任何内容。

如何正确传递content参数?

【问题讨论】:

  • “可以包含任何东西”是什么意思?你想把组、版本、id、env等所有字段都封装到内容中,对吗?
  • @pvpkiran 不,是一个新字段,我可以在其中放置代码或键/值行,例如...我不知道是否可以按照我的要求做?
  • 某事要么是@RequestBody 要么是@RequestParam 不是两者都...

标签: spring rest spring-boot swagger


【解决方案1】:

像这样声明一个类

class PostBody{
   Map<String, String> content;
}

将此 PostBody 用作 @RequestBody。您可以将任何字符串键值对传递给此结构。像这样的

{
"content":
    {
      "version" : "1.1",
      "env" : "test"
    }  
}

{
"content":
    {
      "version" : "1.1",
      "env" : "test",
      "id" : "1.1"
    }  
}

【讨论】:

  • 我有这个错误响应正文 { "timestamp": 1496133459278, "status": 500, "error": "Internal Server Error", "exception": "java.lang.IllegalArgumentException", " message": "'Content-Type' 不能包含通配符类型'*'", "path": "/api/test/uploadProperties" }
  • 错误很明显,我猜Content-Type' cannot contain wildcard type '*' 你正在传递 * 内容类型。你怎么称呼这个休息端点?
  • curl -X POST --header "Content-Type: */*" --header "Accept: */*" -d "{ \"content\": { \"version\" : \"1.1\", \"env\" : \"test\", \"id\" : \"1.1\" } }" "http://localhost:8080/api/test/uploadProperties?group=a&amp;id=a&amp;version=a&amp;env=a"
  • 几件事。正如@Deinum 所说,您将requestparms 与requestbody 混合在一起,当您拥有requestbody 时,为什么还要传递请求参数(在“?”之后的url 中)。在您的 curl 中,您的内容类型到底是什么?
猜你喜欢
  • 1970-01-01
  • 2016-11-17
  • 2019-05-19
  • 2023-02-24
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2012-12-18
  • 2020-05-10
相关资源
最近更新 更多