java - Jersey @Consumes 端点如何匹配?

标签 java rest jersey jax-rs jersey-2.0

我正在设计一个 RESTful 端点来接收文件。我希望它接受 POSTing 作为纯文件/流和多部分。 servlet 容器如何匹配端点有规则吗?下面的代码能可靠地工作吗,或者这个实现是特定的?我可以使用 WILDCARD,还是必须将其限制为 APPLICATION_OCTET_STREAM?

@Path("foo")
public class Foo {
    @POST
    @Path("{filename}")
    @Consumes(MediaType.WILDCARD)
    public Response uploadFileDirect(
        @PathParam("filename") String filename,
        InputStream is)
    {
        // process input stream
        Response.ok().build();
    }

    @POST
    @Path("{filename}")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFileMultipart(
        @PathParam("filename") String filename,
        @FormDataParam("file") InputStream is)
    {
        // process input stream
        Response.ok().build();
    }
}

最佳答案

这在 JAX-RS spec 中指定3.7.2 请求匹配

[...]

Resource class/object is found and all resource and sub resource methods are put into set M

[...]

  1. Identify the method that will handle the request:
    a. Filter M by removing members that do not meet the following criteria:
        [...]
    b. Sort M in descending order as follows:
        * The primary key is the media type of input data. Methods whose @Consumes value is the best match for the media type of the request are sorted first.
        * The secondary key is the @Produces value. Methods whose value of @Produces best matches the value of the request accept header are sorted first.

Determining the best matching media types follows the general rule: n/m > n/* > */*, i.e. a method that explicitly consumes the request media type or produces one of the requested media types is sorted before a method that consumes or produces */*.

如果您查看最后一段(确定最佳匹配),它表示 */* (MediaType.WILDCARD) 的优先级最低。更具体的媒体类型将永远获胜。

关于java - Jersey @Consumes 端点如何匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29857643/

相关文章:

eclipse - 如何在 Eclipse 中的 Tomcat 上部署 REST (Jersey) 服务

用于在列表中查找事件的 Java 流

java - "HttpMessageNotReadableException Required request body is missing"尝试发出发布请求时

java - 使用 rxjava 检测文件文本更改

Java 应用程序属性文件

c# - RESTful WCF 服务返回 "The resource cannot be found."错误

java - @ComponentScan 和 @Autowired 无法从特定包注入(inject)

eclipse - Eclipse 可以将 Maven Web 项目导入为 "Dynamic Web Application"吗?

java - 使用 REST API 在 Jira 中创建问题

rest - 如何使用 Jersey API 或任何其他 jax-rs API 在 jax-rs 中使用 @HEAD?