我编写了一个REST调用,它将在调用时返回健康状态
@RestController
@RequestMapping(value = "/account")
public class HealthCheckController {
protected final Logger log = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/health", method = RequestMethod.GET, produces = { "application/json" })
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "Returns the health status of the application", notes = "Load balancer user this to confirm the health of the node")
public @ResponseBody String getHealth(HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("***" + RequestCorrelation.getId() + "***" + "HealthCheckController - getHealth () Called");
return "{\"health\":{\"SERVICES\":\"OK\"}}";
}
}
当我在招摇或邮递员中打开它时,它会返回正确的响应。但是当我在Chrome浏览器中点击此URL时,我看到了
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
为什么这样?以及如何解决这个问题?
答案 0 :(得分:0)
尝试不返回String但
return new ResponseEntity<>(yourString, HttpStatus.OK);
并且也改变了这个
public @ResponseBody String getHealth(HttpServletRequest request, HttpServletResponse response) throws Exception {
到这个
public @ResponseBody ResponseEntity<String> getHealth(HttpServletRequest request, HttpServletResponse response) throws Exception {
如果它不起作用,请尝试在浏览器中访问URL时将.xml或.json添加到URL的末尾。
答案 1 :(得分:0)
遇到同样的问题。有一个具有以下类注释和方法的对象:
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@GET
@Path("version")
public String getVersion() { return "v1"; }
在@Produces 注释的末尾添加了 MediaType.TEXT_PLAIN。没用。 将它移到 @Produces 注释的开头。没用。
将它移动/添加到方法中解决了我的问题。您的客户也需要能够接受该媒体类型。
@GET
@Path("version")
@Produces({MediaType.TEXT_PLAIN})
public String getVersion() { return "v1"; )
HTH
答案 2 :(得分:0)
在您的 getHealth()
方法中,您将返回一个字符串,但在您的 @RequestMapping
注释中,您指定您的方法将生成 JSON。
尝试以下方法之一:
@RequestMapping(value = "/health", method = RequestMethod.GET, produces = { "text/plain" })
//Now, pass Accept = "text/plain" in the request header:
或
@RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
public List<String> getHealth(..) {
/*
...
*/
ArrayList<String> list=new ArrayList();
list.add("Health OK");
return list;
}
这会给你
["Health OK"]
在响应中。