我想创建一个可以返回 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/