如何使用@RestController return 一个简单的布尔值作为纯文本?

How to return a simple boolean value as plain text with @RestController?

我只想通过一个简单的 servlet return 文本 "true":

@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public Boolean isValid() {
    return true;
}

结果:406 - The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers..

为什么?我怎样才能 return 那个简单的值? 如果我将 return 类型更改为 String "true".

则没有区别
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public String isValid() {
   return "true";
}

和 remove/set 适当的 header 值到 accept header 以满足您的要求。

详细了解 http 状态代码 here

似乎 Spring MVC 默认转换器无法将 Boolean 转换为 text/plain。只有当我尝试使用 Accept: application/json 请求时它才有效。

我建议将 return 类型更改为 String,因为这是您想要 return 的类型。

@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public String isValid() {
    return Boolean.TRUE.toString();
}

这样,没有 Accept header 的请求也可以正常工作,但如果需要,您也可以添加 Accept: text/plain