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

mar*_*rea 6 java rest

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

restServlet /发动机/ 2WS2345

jsonServlet /发动机/ 2WS2345

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

Bru*_*uno 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

内容协商通过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>

有一个默认的媒体类型映射扩展列表,但可以通过MetadataService进行配置.


Sou*_*mya 4

如果您使用 jersey,您可以使用 @Produces 注释轻松配置该方法。@Produces({"application/xml", "application/json"})

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

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