+

Search Tips   |   Advanced Search

Implement content negotiation based on URL patterns

Resources can represent data in different formats. We can implement content negotiation based on URLs, request parameters, or HTTP headers. This task describes content negotiation based on URL patterns. Content negotiation using URLs is the simplest type of content negotiation. This type of content negotiation always returns the same content with the same media type for a given URL. Use the URI defined in the @Path annotation to determine the content type for data returned to the server.

The following example illustrates content negotiation performed at the URL level. A request to /resources/myresource.xml returns the resource representation in XML. A request to...

...returns the resource representation in JSON.

@Path("/resources")
public class Resource 
{
    @Path("{resourceID}.xml")
    @GET public Response getResourceInXML(@PathParam("resourceID") String resourceID) 
    {
        return Response.ok(entity_in_XML_format).type(MediaType.APPLICATION_XML).build();
    }

    @Path("{resourceID}.json")
    @GET
    public Response getResourceInJSON(@PathParam("resourceID") String resourceID) 
    {
        return Response.ok(entity_in_JSON_format).type(MediaType.APPLICATION_JSON).build();
    }
}


Related tasks

  • Use content negotiation to serve multiple content types in JAX-RS applications
  • Implement content negotiation based on HTTP headers
  • Implement content negotiation based on request parameters
  • Web services specifications and APIs