问题描述
我已经使用Jersey实现了REST服务,该服务接受JSON POST数据并根据POJO模型创建对象.但是,为了使其正常工作,我必须将Content-Type设置为application/json(即-H "Content-Type: application/json"
).我想要的是能够使用JSON POST请求主体而无需用户设置标题,基本上就像Elasticsearch的工作一样:
I have implemented a REST service using Jersey that takes JSON POST data and creates an object from a POJO model. However, in order for this to work, I have to set the Content-Type to application/json (i.e., -H "Content-Type: application/json"
). What I'd like is to be able to consume JSON POST request body without the user having to set the header, basically like Elasticsearch works:
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
标头,直至注释中指定的任何内容.
I faced a similar problem. Since in my opinion a well defined API - which doesn't share its endpoints with any other system - should not need to depend on clients specifying the correct Content-Type
, I created a workaround. In this workaround, I add an annotation to those resource methods where I want Jersey to always attempt to read the input according to a server-defined Content-Type
. Whenever this annotation is present, a ResourceFilter
will override the Content-Type
header in the request, to whatever is specified in the annotation.
我在在这里我的答案中详细介绍了该过程.
I have detailed the process in my answer here.
这篇关于JAX-RS:在不将Content-Type标头设置为application/json的情况下使用JSON POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!