[英]Restlet using custom media type
在Restlet 2.3(SE)中,我试图使用媒体类型来控制版本。 我当前的尝试涉及在入站路由中注册新的扩展:
@Override
public Restlet createInboundRoot() {
...
getTunnelService().setExtensionsTunnel(true);
getMetadataService().addExtension("vnd.myapp.v1", MediaType.valueOf("application/vnd.myapp.v1+json"));
getMetadataService().addExtension("vnd.myapp.v2", MediaType.valueOf("application/vnd.myapp.v2+json"));
...
}
然后,按如下所示设置我的资源接口:
public interface UsersResource {
@Options
void getCorsSupport();
@Get("vnd.myapp.v1")
Collection<User> representV1() throws Exception;
// Should be the default if */* is specified
@Get("json | vnd.myapp.v2")
Collection<User> representV2() throws Exception;
}
然后,我尝试如下指定媒体类型:
http://localhost:8080/api/users?media=vnd.myapp.v1
这个想法是,如果有人将媒体类型指定为vnd.myapp.v1
它们将得到representV1()
vnd.myapp.v1
representV1()
(JSON),如果他们将媒体类型指定为vnd.myapp.v2
,则它们将得到vnd.myapp.v2
representV2()
(JSON),并且(可选)他们不要求任何特定的东西,他们得到了representV2()
。 通过上面的设置,无论请求什么,我总是会返回representV2()
。
这是我测试时得到的:
Accept: application/vnd.myapp.v1+json
> representV1
Accept: application/vnd.myapp.v1+json
被调用 Accept: application/vnd.myapp.v2+json
> representV2
Accept: application/vnd.myapp.v2+json
被调用 Accept: application/application/json
> representV1
Accept: application/application/json
被调用 Accept: */*
-> representV1
被调用 似乎表达式json | vnd.myapp.v2
json | vnd.myapp.v2
无法正常工作。 解决方法是使用json
和vnd.myapp.v2
分为两个方法。
当没有指定accept头时,Restlet似乎会调用第一个带有注解Get
it find的方法。
可以帮助您启用跟踪功能以查看不同方法的分数的方法是:
public class RestletLauncher {
public static void main(String[] args) {
Engine.getInstance().setLogLevel(Level.FINEST);
launchApplication();
}
}
您会看到类似的痕迹:
Score of annotation "MethodAnnotationInfo [javaMethod: public org.restlet.representation.Representation test.MyServerResource1.testGetVnd1(), javaClass: class test.MyServerResource1, restletMethod: GET, input: vnd.myapp.v1, value: vnd.myapp.v1, output: vnd.myapp.v1, query: null]"= 0.5
Total score of variant "[application/vnd.myapp.v1+json]"= 0.04191667
Score of annotation "MethodAnnotationInfo [javaMethod: public org.restlet.representation.Representation test.MyServerResource1.testGetJson(), javaClass: class test.MyServerResource1, restletMethod: GET, input: json, value: json, output: json, query: null]"= 0.5
Total score of variant "[application/json]"= 0.04191667
Score of annotation "MethodAnnotationInfo [javaMethod: public org.restlet.representation.Representation test.MyServerResource1.testGetVnd2(), javaClass: class test.MyServerResource1, restletMethod: GET, input: vnd.myapp.v2, value: vnd.myapp.v2, output: vnd.myapp.v2, query: null]"= 0.5
Total score of variant "[application/vnd.myapp.v2+json]"= 0.04191667
希望对您有帮助,蒂埃里
在注释中删除空格字符时,效果会更好:
@Get("json|vnd.myapp.v2")
我输入了一个问题来解决此问题。 https://github.com/restlet/restlet-framework-java/issues/1099
此致Thierry Boileau
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.