Dropwizard Response.status(Response.Status.NOT_FOUND).build() returns html

Dropwizard Response.status(Response.Status.NOT_FOUND).build() returns html

万一真正缺少资源,我的APIreturn如下

{
    "code": 404,
    "message": "HTTP 404 Not Found"
}

当我使用代码 Response.status(Response.Status.NOT_FOUND).build() 通过我的资源 return 404 时,我得到以下 HTML 作为响应

<html>

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>Error 404 Not Found</title>
</head>

<body>
    <h2>HTTP ERROR 404 Not Found</h2>
    <table>
        <tr>
            <th>URI:</th>
            <td>/v1/2/1/100</td>
        </tr>
        <tr>
            <th>STATUS:</th>
            <td>404</td>
        </tr>
        <tr>
            <th>MESSAGE:</th>
            <td>Not Found</td>
        </tr>
        <tr>
            <th>SERVLET:</th>
            <td>io.dropwizard.jersey.setup.JerseyServletContainer-21c99abf</td>
        </tr>
    </table>

</body>

</html>

我正在想办法阻止这个意外的 HTML 并在没有数据的情况下进行响应。

我们遇到了同样的问题,通过将 .entity(...) 设置为空字符串解决了这个问题:

Response.status(NOT_FOUND).entity("").type(MediaType.APPLICATION_JSON).build()

由于这是一种 hack,我也很想了解更清洁的解决方案...;)

将球衣 属性 ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR 设置为 true

environment.jersey()
        .property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, true);

public static final String RESPONSE_SET_STATUS_OVER_SEND_ERROR

Whenever response status is 4xx or 5xx it is possible to choose between sendError or setStatus on container specific Response implementation. E.g. on servlet container Jersey can call HttpServletResponse.setStatus(...) or HttpServletResponse.sendError(...).

Calling sendError(...) method usually resets entity, response headers and provide error page for specified status code (e.g. servlet error-page configuration). However if you want to post-process response (e.g. by servlet filter) the only way to do it is calling setStatus(...) on container Response object.

If property value is true the method Response.setStatus(...) is used over default Response.sendError(...).

Type of the property value is boolean. The default value is false.

The name of the configuration property is "jersey.config.server.response.setStatusOverSendError".