【问题标题】:play framework content type application/xml播放框架内容类型 application/xml
【发布时间】:2012-11-01 02:08:29
【问题描述】:

我正在使用 Play 实现一个 REST Web 服务! 2.0.4 版。

经过几次测试 - 使用 curl 请求资源 - 我注意到 Play!仅接受具有以下 Content-Type 的 XML:text/xml。根据 W3,text/xml 和 application/xml 都是有效的 MIME 类型。

发件人:http://www.w3.org/TR/xhtml-media-types/

也可以使用媒体类型“application/xml”和“text/xml”,但是 在适当的时候,'application/xhtml+xml' 或 'text/html' 应该是 使用而不是那些通用的 XML 媒体类型。

问题。在我的代码中,我有类似的东西:

106: if (request().getHeader("Content-Type").contains("text/xml")
107:            || request().getHeader("Content-Type").contains("application/xml")) {
108:        
109:        Document xml = request().body().asXml();
110:        Node root = XPath.selectNode("cost", xml);
        ...
}

如果 Content-Type 等于 text/xml 一切正常,但对于其他站点,如果 Content-Type 等于 application/xml 则播放!框架在赋值Document xml = request().body().asXml();中返回null

以下是我用来测试 Web 服务的列表命令 - 使用 curl:

$ curl -i -X POST -d @input.xml -H "Content-Type: text/xml" \
http://localhost:9000/costs

HTTP/1.1 200 OK
Content-Type: text/xml
Content-Length: 146

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><cost>3089219.0</cost>

$ curl -i -X POST -d @input.xml -H "Content-Type: application/xml" \
http://localhost:9000/costs

HTTP/1.1 500 Internal Server Error
Content-Type: text/html; charset=utf-8
Content-Length: 5231

...
[RuntimeException: java.lang.RuntimeException: java.lang.NullPointerException]
In (...)/app/controllers/Application.java at line 110.
...

这是一个错误还是正常行为?

谢谢!

里卡多·F·特谢拉

【问题讨论】:

    标签: xml playframework mime-types content-type


    【解决方案1】:

    现在我不一定能够回答这是否是故意的,但我也遇到了同样的问题并为这种情况设法解决了。

    您应该能够收到您的request().body().asRaw().asBytes(),这将返回一个byte[]

    从那里,它可以用来构造一个ByteArrayInputStreamDocument 将接受它作为它自己构造的参数。

    DocumentBuilder docBuilder = DocumentBuilderFactory().newInstance().newDocumentBuilder();
    Document xml = docBuilder.parse(new ByteArrayInputStream(request().body().asRaw().asBytes()));
    

    【讨论】:

    • 好吧,我想我会使用你的方法 :) 总比没有好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多