从HTTP响应标头中丢失

时间:2017-07-17 08:03:41

标签: java http tomcat servlets

我在Tomcat 8中部署了一个webapp。这是我遇到问题的servlet:

@WebServlet(name = "Start", urlPatterns = {"/start"})
public class StartServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestBodyStr = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        StartRequest startRequest = JsonUtil.parseStartRequest(requestBodyStr);

        if (startRequest == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        response.setStatus(HttpServletResponse.SC_OK);

        String responseBody = getResponseBody();

        try (PrintWriter out = response.getWriter()) {
            out.print(responseBody);
        }
    }
}

如果我向这个servlet发出请求,那么响应中不包含OK状态消息,它只是:

HTTP/1.1 200

如何在回复中添加确定?

1 个答案:

答案 0 :(得分:1)

当你执行response.setStatus(HttpServletResponse.SC_OK);时,它与执行response.setStatus(200);相同(从字面上看,如果你检查它,SC_OK只是一个值为200的常量)。 200是http中OK的代码。如果您想手动编写 OK,则必须添加:

responserBody += " OK";
try (PrintWriter out = response.getWriter()) {
    out.print(responseBody);
}

但这不应该有用,因为200已经说过:请求按预期工作。