【问题标题】:Spring-boot ResponseEntity body missing for non-200 status codes非 200 状态码的 Spring-boot ResponseEntity 主体缺失
【发布时间】:2019-12-23 09:32:37
【问题描述】:

TLDR;如何使用 Spring ResponseEntity 在正文中发送文本消息以及 304 状态代码?

上下文

我正在用 Spring-boot 编写一个 REST API。在某些端点,我想返回:

  • 任一状态200 OK 和正文Success
  • 或状态304 NOT MODIFIED 与正文Not modified.

我的端点以下列方式使用 ResponseEntity(在 kotlin 中):

@PutMapping("/test")
fun modifyStuff(): ResponseEntity<String> {
    if (someCondition)
        // "not modified" not sent in the body
        return ResponseEntity("not modified", HttpStatus.NOT_MODIFIED)

    // using OK, it works
    return ResponseEntity("success", HttpStatus.OK)
}

问题

每当我创建一个状态码为 != 200 的 ResponseEntity 时,都不会发送正文(空正文)。将HttpStatus 更改为OK 会使消息再次显示...我不想为未修改创建错误处理程序,因为这绝对不是错误。

【问题讨论】:

标签: spring spring-boot kotlin


【解决方案1】:

早期有较早的标准 RFC2616,现在您可以参考较新的 RFC 7230-7237,它们都提到 304 响应不应包含正文。

特别是较旧的 RFC2616 表示“不得包含正文”和较新的 RFC7230 “所有 1xx(信息)、204(无内容)和 304(未修改)响应不包含消息正文 " 最后,一些服务器可能会发送或接受具有此状态的正文,但 spring ResponseEntity 并非如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2018-11-10
    相关资源
    最近更新 更多