【问题标题】:How to return a boolean value with rest?如何在休息时返回布尔值?
【发布时间】:2015-05-03 22:22:57
【问题描述】:

我想提供一个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.

【问题讨论】:

  • 试着用一个布尔属性(状态或者你喜欢的)创建一个@XMLRootElement。
  • 好的,我明白了。但是如果我返回纯文本真/假就足够了。我绑定了MediaType.TEXT_HTML_VALUE,但遇到了同样的 406 错误。
  • "根据请求“accept”标头不可接受"您是如何尝试的?
  • 刚刚在webbrowser(firefox)中打开了rest url。

标签: java spring rest spring-boot


【解决方案1】:

您不必删除@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();
}

【讨论】:

  • 它不起作用,我只得到真值,但测试用例失败,因为它期望响应以 {(大括号)开始
  • @JitendraVispute 很好,它确实有效,“只获得真正的价值”是最初的问题。看起来您的测试用例正在寻找要返回的 JSON 对象。我猜不同的问题。我们可能还需要更多细节。
  • 在没有@ResponseBodyMediaType 的情况下对我有用
猜你喜欢
  • 2019-06-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2013-03-28
  • 2015-04-07
  • 2013-08-18
  • 1970-01-01
相关资源
最近更新 更多