gpt4 book ai didi

java - JAX RS POST API 不支持 HEAD 请求

转载 作者:行者123 更新时间:2023-12-02 03:14:52 26 4
gpt4 key购买 nike

根据 Jersey 文档,

By default the JAX-RS runtime will automatically support the methods HEAD and OPTIONS, if not explicitly implemented. For HEAD the runtime will invoke the implemented GET method (if present) and ignore the response entity (if set). For OPTIONS the Allow response header will be set to the set of HTTP methods support by the resource. In addition Jersey will return a WADL document describing the resource.

所以,如果我有一件 Jersey POST API,会不会不支持HEAD称呼?就我而言,它仅支持 OPTIONS调用,返回允许的方法为 POSTOPTIONS 。您如何支持 HEAD调用?

最佳答案

您给出的引文回答了您问题的一半:

For HEAD the runtime will invoke the implemented GET method (if present) and ignore the response entity (if set).

因此,要在您的端点上启用 HEAD 方法,您有两个选择:

  • 实现 GET 和 Jersey 将自动提供 HEAD 的默认实现
  • 显式实现 HEAD

POST 方法不能用于提供默认 HEAD 实现的原因是 POST 方法既不安全也不幂等(如 HTTP 标准中所定义)。这意味着如果有人调用 POST 方法,他们必须假设它将对应用程序/资源状态产生影响。另一端的 GET 和 HEAD 都是安全且幂等的,因此它们不能改变状态。

回答问题的第二部分 - 实现 HEAD 与实现其他 HTTP 方法没有什么不同:

import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("api/ping")
public class MyResource {

@GET
@Produces(MediaType.TEXT_PLAIN)
public String ping() {
return "pong!";
}

@HEAD
public Response getHeaders() {
return Response.status(200).
header("yourHeaderName", "yourHeaderValue").build();
}
}

关于java - JAX RS POST API 不支持 HEAD 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40464275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com