Java 根据MIME类型处理REST请求

Java 根据MIME类型处理REST请求,java,rest,post,jersey,mime-types,Java,Rest,Post,Jersey,Mime Types,我有一个名为createCustomer的方法,它是一个POST方法,它同时使用MediaType.APPLICATION_XML、MediaType.APPLICATION_JSON,现在我想检查来自客户端的请求的实际MIME类型,它可以是XML或JSON,根据请求的MIME类型,我想调用两个不同的方法 你能给我提供代码来检查传入请求的MIME类型和基于类型调用的两种不同方法吗 示例代码如下所示: @POST @Path("/createCustomer") @Consumes({MediaT

我有一个名为createCustomer的方法,它是一个POST方法,它同时使用MediaType.APPLICATION_XML、MediaType.APPLICATION_JSON,现在我想检查来自客户端的请求的实际MIME类型,它可以是XML或JSON,根据请求的MIME类型,我想调用两个不同的方法

你能给我提供代码来检查传入请求的MIME类型和基于类型调用的两种不同方法吗

示例代码如下所示:

@POST
@Path("/createCustomer")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response createCustomer(Customer customer ) {
    //if the request is in JSON then call the method createCustomerJSON()
    //else if the request is in XML then call the method createCustomerXML()

    //String output = output from either the method createCustomerJSON() or createCustomerXML()

    return Response.status(200).entity(output).build();
}
注释可能是您需要的。通过在不同的方法上添加不同的注释,可以拆分XML和JSON的处理

从javadoc:

定义资源类或MessageBodyReader的方法可以接受的媒体类型。如果未指定,容器将假定任何媒体类型都是可接受的。方法级注释重写类级注释。容器负责确保调用的方法能够使用HTTP请求实体体的媒体类型。如果没有此类方法可用,则容器必须使用RFC 2616指定的HTTP 415不支持的媒体类型进行响应


首先,发布一些代码会很好

其次,一种解决方案是创建两个具有相同路径的方法,一个使用XML,另一个使用JSON

@POST
@Path("yourPath")
@Consumes(MediaType.APPLICATION_XML);
public Response createCustomerXML() {...}

@POST
@Path("yourPath")
@Consumes(MediaType.APPLICATION_JSON);
public Response createCustomerJSON() {...}