首页 > 解决方案 > 非 200 状态码的 Spring-boot ResponseEntity 主体缺失

问题描述

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

语境

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

我的端点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)
}

问题

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

标签: springspring-bootkotlin

解决方案


Earlier there was earlier standard RFC2616 and now you can refer to newer RFC 7230-7237 and both of them mention 304 response should not include body.

Specifically older RFC2616 says it "must not include body" and newer RFC7230 "All 1xx (Informational), 204 (No Content), and 304 (Not Modified) responses do not include a message body" In the end some servers might send or accept body with this status but it is not the case for spring ResponseEntity.


推荐阅读