【问题标题】:Restlet does not differentiate between different Accept HeadersRestlet 不区分不同的 Accept Headers
【发布时间】:2014-09-05 17:33:14
【问题描述】:

在我的 ServerResource 中有两个不同的“Get-Functions”

public class ApiKeyRestlet extends ServerResource {

@Get("json:json")
public ApiKeyResponse apikeyAsJson() throws RecordDoesNotExist {
   ...
}

@Get("text:text")
public Representation apikeyAsFile() throws RecordDoesNotExist {
    ... 
    Representation representation = new StringRepresentation(data, MediaType.TEXT_PLAIN);
    Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
    disposition.setFilename("apikey.properties");
    representation.setDisposition(disposition);

    return representation;
}
...

路径 .../apikey 绑定到 ApiKeyRestlet。如果客户端发送 Accept: text/plain 然后 apikeyAsFile 应该被调用,如果客户端发送 Accept: application/json apikeyAsJson 应该生效。但是我可以将我想要的作为 Accept-Header 发送,它总是被称为 apikeyAsJson。

我认为这与这两种格式之间的兼容性有关,但我该如何处理呢?我不想为此定义两条不同的路线。

[更新] 我通过代码调试,发现Representation的返回类型添加了默认的MediaType [*/*]。得分总是 0.5,所以总是会调用 ServerResource 中定义的第一个函数 - 似乎是一个错误???如果我定义了一个 Accept-Header,这个请求的分数应该会上升......

【问题讨论】:

标签: java restlet restlet-2.0


【解决方案1】:

是的,您在注释中使用了错误的值。实际上,该值对应于 Restlet 所称的扩展。后者映射一组媒体类型。例如:

  • 扩展xml 映射到媒体类型application/xmltext/xml
  • 扩展txt 映射到媒体类型text/plain

您可以在方法MetadataService#addCommonExtensions 级别访问javadocs (http://restlet.com/technical-resources/restlet-framework/javadocs/2.2/jse/api/) 中所有受支持的扩展。该方法负责注册所有支持的扩展。

在你的情况下,我会像这样重构你的代码:

public class ApiKeyRestlet extends ServerResource {
    @Get("json")
    public ApiKeyResponse apikeyAsJson() throws RecordDoesNotExist {
        (...)
    }

    @Get("txt")
    public Representation apikeyAsFile() throws RecordDoesNotExist {
        (...)
    }
}

如果标题 Accept 包含 application/json 和方法 apikeyAsFiletext/plain,则将调用方法 apikeyAsJson

希望对你有帮助 蒂埃里

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多