繁体   English   中英

Spring Rest Service Call 在第 1 行第 1 列返回错误:文档为空

[英]Spring Rest Service Call returning error on line 1 at column 1: Document is empty

我写了一个 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\"}}";
    }

}

当我在 swagger 或 postman 中打开它时,它会返回正确的响应。 但是当我在 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.

为什么会这样? 以及如何解决这个问题?

有同样的问题。 有一个具有以下类注释和方法的对象:

@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

在您的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"]

尝试返回不是字符串而是

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 {

如果它不起作用,当您在浏览器中访问它时,尝试将 .xml 或 .json 添加到您的 URL 的末尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM