2015-06-08 57 views
1

在Restlet 2.3(SE)我試圖使用媒體類型來控制版本。我當前的嘗試包括在我的呼入路由註冊新的擴展:Restlet使用自定義媒體類型

@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()(JSON),如果他們指定媒體類型爲vnd.myapp.v2他們得到representV2()(JSON)和(可選),如果他們沒有要求任何具體的東西representV2()。有了上述設置,無論要求什麼,我總是會回到representV2()

回答

1

這裏是我有什麼,當測試:

  • Accept: application/vnd.myapp.v1+json - >representV1
  • Accept: application/vnd.myapp.v2+json - >representV2
  • Accept: application/application/json - >representV1
  • Accept: */* - >representV1是稱爲

看來,表達式json | vnd.myapp.v2無法正常工作。解決方法是將代表V2分成兩個方法,分別爲jsonvnd.myapp.v2

當沒有指定accept頭時,Restlet似乎會調用第一個方法,它找到了註釋Get

的東西,可以幫助你,是讓痕跡,看到的不同的方法得分:

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 

希望它可以幫助你, Thierry