Returning 200 response code instead of 204

人盡茶涼 提交于 2019-12-13 04:23:20

问题


This is my method for creating Response with header parameters and body:

public Response sendOKResponse(request req)
{
    ResponseBuilderImpl builder = new ResponseBuilderImpl();
    // set the header params.
    for(int index =0; index<req.headerParameters.size(); index++)
    {
        builder.header(req.headerParameters.get(index).getName(), req.headerParameters.get(index).getBody());
    }

    // set the body and response code
    builder.status(Response.Status.OK).entity(req.getBody());
    Response r = builder.build();
    return r;
}

And this is how i return the Response:

Response response;
response = sendBadMesseage();
        return response;

This code returns code 204(No content) instead of 200. Any ideas why?


回答1:


You shouldn't be instantiating your response builder with new, the whole point of the JAX-RS abstraction layer is to hide implementation details away from calling clients. This is what makes it possible to have various vendor implementations which can be interchanged at will. Also, if you are using JEE6, or hope to migrate to it, this code will almost certainly fail. Most JEE6 vendor implementations utilize CDI, which is concept-incompatible with usage of new. But, closer to the topic, the JAX-RS implementation specifies that a 204 status code be returned if a responses wrapped entity is null. You might want to verify this is not the case in any of your methods. Also, you might want to make some changes to your code:

public Response sendOKResponse(request req) {
    ResponseBuilder response = Response.ok();

    // set the header params.
    for(Header h: req.headerParameters()) {
        builder = builder.header(h.getName(), h.getValue());
    }

    // set the body and response code
    builder = builder.entity(req.getBody());

    return builder.build();
}

Your sendBadMessage method should also look similar to above. You can log your entity before adding it to the builder, to verify that you only get a 204 when it's null.



来源:https://stackoverflow.com/questions/9344054/returning-200-response-code-instead-of-204

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!