具有相同REST GET的多个响应类型?

时间:2010-06-24 13:15:29

标签: java rest

我想创建一个可以返回JSON或XML的REST服务。我在请求中设置什么请求参数来请求某个mime类型?我知道如何在响应中设置它,但必须有一种方法来请求某个。目前我在URL中执行此操作

restServlet /发动机/ 2WS2345

jsonServlet /发动机/ 2WS2345

这让我得到了json或xml。但我想我读过在请求中设置了一个参数。我正在使用JAVA ......

2 个答案:

答案 0 :(得分:5)

您可以使用代码中的注释Restlet执行此操作,并根据用户代理的Accept标头进行内容协商操作,或者在URI中指定扩展名(使用Restlet的TunnelService和MetadataService)。这是一个例子(基于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();
    }
}

内容协商通过Accept标头工作:

  • curl -H "Accept: text/plain" http://localhost:8182/test返回Hello!
  • curl -H "Accept: application/xml" http://localhost:8182/test返回<test>Hello</test>

它也适用于扩展程序(感谢getTunnelService().setExtensionsTunnel(true)):

  • curl http://localhost:8182/test.txt返回Hello!
  • curl http://localhost:8182/test.xml返回<test>Hello</test>

default list of extension to media-type mapping,但可以通过MetadataService配置。

答案 1 :(得分:4)

如果您正在使用运动衫,则可以使用@Produces注释轻松配置方法。    @Produces({“application / xml”,“application / json”})

好的是你仍然可以将JAXB对象作为返回类型。它将自动更改为所需的格式。除非在Accept Header中指定MIME类型,否则它将始终在上述情况下发送xml。

参考http://jersey.java.net/nonav/documentation/1.6/user-guide.html