我已经使用 Jersey 实现了一个 REST 服务,该服务获取 JSON POST 数据并从 POJO 模型创建一个对象。但是,为了使其工作,我必须将 Content-Type 设置为 application/json(即 -H "Content-Type: application/json"
)。我想要的是能够在用户无需设置 header 的情况下使用 JSON POST 请求正文,基本上就像 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());
}
最佳答案
我遇到了类似的问题。由于在我看来定义良好的 API(不与任何其他系统共享其端点)不应依赖于指定正确的 Content-Type
的客户端,因此我创建了一个解决方法。在此解决方法中,我向那些我希望 Jersey 始终尝试根据服务器定义的 Content-Type
读取输入的资源方法添加注释。只要存在此注释,ResourceFilter
就会覆盖请求中的 Content-Type
header ,以注释中指定的任何内容。
我在my answer here中有详细的过程.
关于java - JAX-RS:在不将 Content-Type header 设置为 application/json 的情况下使用 JSON POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35823773/