如何用rest返回一个布尔值?

我想提供一个只提供true / false布尔响应的boolean REST服务。

但以下不起作用。 为什么?

 @RestController @RequestMapping("/") public class RestService { @RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public Boolean isValid() { return true; } } 

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

您不必删除@ResponseBody ,您可能刚刚删除了MediaType

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

在这种情况下,它将默认为application/json ,所以这也可以工作:

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

如果您指定MediaType.APPLICATION_XML_VALUE ,您的响应实际上必须可序列化为XML,这是true不可能。

另外,如果你只是想在响应中使用简单的true ,那么它不是真正的XML吗?

如果你特别想要text/plain ,你可以这样做:

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