2015-03-03 42 views
4

我想提供僅提供真/假布爾響應的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.

+0

只是嘗試創建一個@XmlRootElement只是一個布爾屬性(身份或你喜歡的一個)。 – alphamikevictor 2015-03-03 10:06:37

+0

好的,我明白了。但是,如果我將純文本返回true/false就足夠了。我綁定了「MediaType.TEXT_HTML_VALUE」,但得到了相同的406錯誤。 – membersound 2015-03-03 10:08:34

+1

「*根據請求無法接受」接受「標題*」您是如何嘗試它的? – cy3er 2015-03-03 10:12:14

回答

9

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