如何返回带有休息的布尔值

如何返回带有休息的布尔值

本文介绍了如何返回带有休息的布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

结果: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:

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

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

在这种情况下,它将默认为application/json,因此也可以使用:

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

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

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

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

此外,如果您只想在响应中输入普通的true,那不是真的XML吗?

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

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

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

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

这篇关于如何返回带有休息的布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:16