質問

I don't understand why javax.ws.rs.Produces can take more than two Media types. As I know, web service client must know exactly what is media type return by the web service. I took a look at its API at http://docs.oracle.com/javaee/6/api/javax/ws/rs/Produces.html but I didn't find my answer. Anyone has any ideas? Thanks.

役に立ちましたか?

解決

A restful endpoint can return any number of media types. This allows the service to support multiple clients that may have different requirements. The clients tell the service what content type they expect to be returned by setting the Accept header or in some cases using a special suffix on the url like .json or .xml.

Example:

Let's pretend you have two clients calling the same web service.

  • Client A may only be able to parse XML. So they request an XML response by sending application/xml in the Accept header.

  • Client B may be able to parse both XML and JSON, but they prefer JSON. So they send application/json in the Accept header.

In order for the restful endpoint to support both of these requests it would be annotated as follows:

@GET
@Produces({"application/json", "application/xml"})
public Foo getFoo()
{
   return Foo();  //This will be marshalled to XML or JSON depending on what the client requests
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top