Java 如何在休息时返回布尔值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28828896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:54:50  来源:igfitidea点击:

How to return a boolean value with rest?

javaspringrestspring-boot

提问by membersound

I want to provide a booleanRESTservice that only provides true/false boolean response.

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

But the following does not work. Why?

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

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

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

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

采纳答案by ci_

You don't have to remove @ResponseBody, you could have just removed the MediaType:

您不必删除@ResponseBody,您可以删除MediaType

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

in which case it would have defaulted to application/json, so this would work too:

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

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

if you specify MediaType.APPLICATION_XML_VALUE, your response really has to be serializable to XML, which truecannot be.

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

Also, if you just want a plain truein the response it isn't really XML is it?

另外,如果您只想要一个简单true的响应,它实际上不是 XML,是吗?

If you specifically want text/plain, you could do it like this:

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

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