gpt4 book ai didi

java - 使用自定义媒体类型的 ReSTLet

转载 作者:行者123 更新时间:2023-11-30 03:24:00 32 4
gpt4 key购买 nike

在 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"));

...
}

我的资源接口(interface)设置如下:

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()

最佳答案

这是我测试时的结果:

  • 接受:application/vnd.myapp.v1+json -> representV1 被调用
  • 接受:application/vnd.myapp.v2+json -> 调用representV2
  • 接受:application/application/json -> 调用representV1
  • 接受:*/* -> 调用representV1

看起来表达式 json | vnd.myapp.v2 无法正常工作。解决方法是将representV2分成两个方法:jsonvnd.myapp.v2

当未指定接受 header 时,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

希望对你有帮助蒂埃里

关于java - 使用自定义媒体类型的 ReSTLet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30704998/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com