JAX-RS:消耗 JSON POST 数据,但未将 Content-Type header 设置为 application/json

JAX-RS: Consuming JSON POST data without setting Content-Type header to application/json

我已经使用 Jersey 实现了一个 REST 服务,该服务获取 JSON POST 数据并从 POJO 模型创建一个 object。但是,为了使其工作,我必须将 Content-Type 设置为 application/json(即 -H "Content-Type: application/json")。我想要的是能够使用 JSON POST 请求 body 而无需用户设置 header,基本上就像 Elasticsearch 的作品:

POST /test_index/_search?search_type=count
{
   "aggs": {
      "nested_authors": {
         "nested": {
            "path": "authors"
         },
         "aggs": {
            "author_last_names": {
               "terms": {
                  "field": "authors.last_name"
               }
            }
         }
      }
   }
} 

相关代码如下:

@POST
@Path("/person")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postPerson(PostBody pb) {
    System.out.println(pb.getEmails());
}

想通了。我现在接受 "application/json" 和 "application/x-www-form-urlencoded" 内容类型。这是代码:

@POST
@Path("/person")
@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_FORM_URLENCODED})
@Produces(MediaType.APPLICATION_JSON)
public Response postPerson(String body) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    PostBody pb = mapper.readValue(body, PostBody.class);
    System.out.println(pb.getEmails());
}

不过,经过一番思考,考虑到它包含 JSON 请求 body,我可能应该要求 Content-Type header,但这完全是另一个讨论。

我遇到了类似的问题。由于在我看来定义明确的 API(不与任何其他系统共享其端点)不应依赖于客户端指定正确的 Content-Type,因此我创建了一个解决方法。在此解决方法中,我向那些我希望 Jersey 始终尝试根据 server-defined Content-Type 读取输入的资源方法添加注释。每当存在此注释时,ResourceFilter 将覆盖请求中的 Content-Type header,以注释中指定的任何内容。

我在my answer here里有详细的过程。