返回200而不是204的响应代码

问题描述:

这是我使用标头参数和正文创建Response的方法:

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;

此代码返回代码204(无内容),而不是200. 有什么想法吗?

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

您不应该使用new实例化响应生成器,JAX-RS抽象层的重点是将实现细节隐藏在调用客户端之外.这使得可以具有可以随意互换的各种供应商实现.另外,如果您正在使用JEE6,或者希望迁移到它,则该代码几乎肯定会失败.大多数JEE6供应商实施都利用CDI,该概念与new的使用在概念上不兼容.但是,更接近主题的是,JAX-RS实现指定如果响应包装的实体为null,则返回204状态代码.您可能要验证在所有方法中都不是这种情况.另外,您可能需要对代码进行一些更改:

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();
}

您的sendBadMessage方法也应与上面类似.您可以先记录您的实体,然后再将其添加到构建器中,以验证是否只有204为空.

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.