球衣如何检查请求的数据格式是什么?

How can jersey check what was the requested data format?

我想知道如何检查客户端从 rest 请求的数据 API

例如我 api 喜欢:

@POST
    @Consumes({ MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML  })
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }){
    ...some logic;
    }

如果客户有 header:

Accept: application/xml

我希望他得到与 header 中 application/json 不同的反应。那我能不能想点像

  @POST
        @Consumes({ MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML  })
        @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}){ 
    if ( mediaType.equals("APPLICATION_JSON"){   (its pseudo code)
    blah blah blah}; 
        }}

???

使用 HeaderParam annotation 访问 Accept header 的值。

@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML  })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response myPostService(@HeaderParam("Accept") String accepted, 
                              MyObject inTheRequestBody) {
   MediaType mediaType = MediaType.APPLICATION_JSON; // the default
   if(accepted != null) {
       mediaType = MediaType.valueOf(accepted);
   }
   // service logic
   return Response.ok().entity(/*the object you want to return*/).type(mediaType).build();
}

Jersey 会为您处理序列化,前提是它具有相应的 MessageBodyReader(对于请求 body)和 MessageBodyWriter。如果没有,您可以随时注册自己的,Jersey 将调用它。