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

mem*_*und 8 java rest spring spring-boot

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

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

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

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

ci_*_*ci_ 13

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

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

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

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

如果你指定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();
}
Run Code Online (Sandbox Code Playgroud)