简体   繁体   English

JAX RS POST API不支持HEAD请求

[英]JAX RS POST API not supporting HEAD request

As per the Jersey documentation, 根据泽西岛的文档,

By default the JAX-RS runtime will automatically support the methods HEAD and OPTIONS, if not explicitly implemented. 默认情况下,如果未明确实现,JAX-RS运行时将自动支持HEAD和OPTIONS方法。 For HEAD the runtime will invoke the implemented GET method (if present) and ignore the response entity (if set). 对于HEAD,运行时将调用已实现的GET方法(如果存在),并忽略响应实体(如果设置)。 For OPTIONS the Allow response header will be set to the set of HTTP methods support by the resource. 对于OPTIONS,“允许”响应标头将设置为资源支持的HTTP方法集。 In addition Jersey will return a WADL document describing the resource. 另外,Jersey将返回描述资源的WADL文档。

So, if I have a Jersey POST API, will it not support HEAD call? 因此,如果我有Jersey POST API,它将不支持HEAD调用吗? In my case, it's supporting only OPTIONS call, which returns allowed methods as POST and OPTIONS . 就我而言,它仅支持OPTIONS调用,该调用返回允许的方法为POSTOPTIONS How do you go about supporting the HEAD calll? 您如何去支持HEAD Calll?

The quote you gave answers half of your question: 您提供的报价可以回答一半的问题:

For HEAD the runtime will invoke the implemented GET method (if present) and ignore the response entity (if set). 对于HEAD,运行时将调用已实现的GET方法(如果存在),并忽略响应实体(如果设置)。

So to enable the HEAD method on your enpoint you have two options: 因此,要在您的enpoint上启用HEAD方法,您有两个选择:

  • implement GET and Jersey will automatically provide the default implementation of HEAD 实现GET,Jersey将自动提供HEAD的默认实现
  • implement HEAD explicitly 明确实现HEAD

The reason why POST method cannot be used to provide a default HEAD implementation is that POST method is neither safe nor idempotent (as defined in the HTTP standard). 无法使用POST方法提供默认HEAD实现的原因是POST方法既不安全也不幂等(如HTTP标准所定义)。 This means that if someone calls a POST method they must assume that it will have consequences on the application/resource state. 这意味着,如果有人调用POST方法,则他们必须假定它将对应用程序/资源状态产生影响。 GET and HEAD on the other side are both safe and idempotent so they must not change the state. 另一端的GET和HEAD既安全又幂等,因此它们不得更改状态。

To answer the second part of your question - implementing HEAD doesn't differ from implementing other HTTP methods: 要回答问题的第二部分-实现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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM