java - 具有相同 REST GET 的多种响应类型?

标签 java rest

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

restServlet/engine/2WS2345

jsonServlet/engine/2WS2345

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

最佳答案

您可以使用 Restlet 执行此操作在您的代码中使用注释,或者让内容协商根据用户代理的 Accept 进行操作 header 或在 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 header 工作:

  • 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 ,但这可以通过元数据服务进行配置。

关于java - 具有相同 REST GET 的多种响应类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3110239/

相关文章:

java - 如何按角色限制对 Spring Data REST 投影的访问?

java - View 子类包括什么?

angular - 将字符串类型从 Spring Boot 返回到 Angular

java - JUnit:是否可以在任何断言函数中输出多行消息?

Java 泛型 - 无法使用扩展泛型覆盖方法

php - REST API : Request body as JSON or plain POST data?

javascript - 将 optgroup 添加到使用 REST、jQuery 和 Bootstrap 动态创建的下拉列表

php - 如何防止同时执行多个 REST API?

java - 在简单文件复制 java 程序中调用方法时出现问题

JAVA/Swing(Eclipse): Program works step by step but not in normal execution