我想提供一个 boolean
REST
服务,它只提供 true/false boolean 值响应。
但以下不起作用。为什么?
@RestController
@RequestMapping("/")
public class RestService {
@RequestMapping(value = "/",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public Boolean isValid() {
return true;
}
}
结果:HTTP 406:此请求标识的资源只能根据请求“接受” header 生成具有 Not Acceptable 特征的响应。
最佳答案
您不必删除 @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();
}
关于java - 如何用 rest 返回 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28828896/