tags:

views:

46

answers:

1

I want to create a REST service that can return either JSON or XML. What request parameter do I set in the request to request a certain mime type? I know how to set it in the response, but there must be a way to request a certain one. Currently I do it in the URL

restServlet/engine/2WS2345

jsonServlet/engine/2WS2345

This gets me json or xml. But I thought I read that there is a parameter to set in the request. I am using JAVA...

+2  A: 

You can do this with Restlet using annotations in your code and either let the content-negotiation operate depending on the user-agent's Accept header or specify the extension in the URI (using Restlet's TunnelService and MetadataService). Here is an example (based on Restlet 2):

public class TestApplication extends Application {
    public static class TestResource extends ServerResource {
        @Get("txt")
        public Representation toText() {
            return new StringRepresentation("Hello!",
                MediaType.TEXT_PLAIN);
        }

        @Get("xml")
        public Representation toXml() {
            return new StringRepresentation("<test>Hello</test>",
                MediaType.APPLICATION_XML);
        }
    }

    @Override
    public synchronized Restlet createInboundRoot() {
        getTunnelService().setEnabled(true);
        getTunnelService().setExtensionsTunnel(true);
        Router router = new Router();
        router.attachDefault(TestResource.class);
        return router;
    }

    public static void main(String[] args) throws Exception {
        Component component = new Component();
        component.getServers().add(Protocol.HTTP, 8182);
        component.getDefaultHost().attachDefault(new TestApplication());
        component.start();
    }
}

Content-negotiation works via the Accept header:

It also works via the extension (thanks to getTunnelService().setExtensionsTunnel(true)):

There's a default list of extension to media-type mapping, but this can be configured via the MetadataService.

Bruno
Yes, and thanks. The secret sauce is: req.getHeader("Accept"). This returns a String that one could parse. Here is what I get when I DON'T set it and use a browser: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*Thanks!
sliver