【问题标题】:Dropwizard Response.status(Response.Status.NOT_FOUND).build() returns htmlDropwizard Response.status(Response.Status.NOT_FOUND).build() 返回 html
【发布时间】:2020-08-20 20:53:37
【问题描述】:

如果真正缺少资源,我的 API 会返回以下内容

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

当我使用代码 Response.status(Response.Status.NOT_FOUND).build() 通过我的资源返回 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 并在没有数据的情况下做出响应。

【问题讨论】:

    标签: java jersey dropwizard


    【解决方案1】:

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

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

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

    【讨论】:

    【解决方案2】:

    将 Jersey 属性 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
    

    只要响应状态为 4xx 或 5xx,就可以在特定于容器的 Response 实现中选择 sendErrorsetStatus。例如。在 servlet 容器上 Jersey 可以调用 HttpServletResponse.setStatus(...)HttpServletResponse.sendError(...)

    调用sendError(...) 方法通常会重置实体、响应头并提供指定状态码的错误页面(例如servlet error-page 配置)。但是,如果您想对响应进行后处理(例如通过 servlet 过滤器),唯一的方法是在容器响应对象上调用 setStatus(...)

    如果属性值为true,则使用Response.setStatus(...) 方法而不是默认Response.sendError(...)

    属性值的类型是boolean。默认值为false

    配置属性的名称是"jersey.config.server.response.setStatusOverSendError"

    【讨论】:

    • 这就是我要找的。像魅力一样工作。没有黑客。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2015-08-20
    • 2015-07-10
    相关资源
    最近更新 更多