如何返回带有 rest 的布尔值?

2022-09-03 06:52:36

我想提供一种只提供真/假布尔响应的服务。booleanREST

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

@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.


答案 1

您不必删除 ,您可以直接删除:@ResponseBodyMediaType

@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;
}

如果指定 ,则响应确实必须可序列化为 XML,而不能。MediaType.APPLICATION_XML_VALUEtrue

另外,如果你只想要一个普通的响应,它不是真正的XML,是吗?true

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

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

答案 2