rest/javax/jersey/grizzly:POST 请求的 return OK (200) 响应代码是强制性的吗?

rest/javax/jersey/grizzly: is it mandatory to return OK (200) response code for POST requests?

想象一个 post REST 端点,例如:

@POST
@Path("/cbo/{param1}/{param2}")
public Response updateCbo() {
    //do something
    return Response.status(Response.Status.OK).build();
}

我的问题是:如果一切顺利,return OK 响应更好还是默认响应更好?我看到 GET 查询通常不会打扰 return 响应,只是请求的内容,网络客户端确实会获取 200 OK header.

谢谢。

您根本不需要 return 响应,假设您有一个 POST(或任何其他函数)类型调用,您希望在响应请求中 return 一个字符串(或者任何对象,如果你使用像 Jackson 这样的序列化程序)

你可以这样做:

@POST
@Path("/cbo/{param1}/{param2}")
public String updateCbo() {
    //do something
    return "My Response"
}

泽西岛将为此自动 return 200。如果将函数设置为 void,Jersey 将自动 return 204(成功 - 无内容)。

如果你想让调用失败,你可以抛出异常。

当POSTing to create一个新的资源时,一般accept away是发回一个201 Created status, with the Location header set the URI of the new resource. You can see an example of one to accomplish this, in this post.

如果您只是 更新 一个资源,而不是 POST,通常是使用 PUT 完成的,那么一般的方法是发送而不是 201 204 无内容,表示成功。例子

@PUT
@Path("/cbo/{param1}/{param2}")
public Response updateCbo(Model updated,
                          @PathParam("param1") String param1,
                          @PathParam("param2") String param2) {
    Model model = modelServive.lookup(param1, param2);
    if (model == null) 
        return Response.notFound().build();
    model = PropTranferUtils.transfer(model, updated);
    modelService.update(model);
    return Response.noContent().build();
}