【问题标题】:POST XML data with Groovy HTTPBuilder使用 Groovy HTTPBuilder 发布 XML 数据
【发布时间】:2012-06-13 14:30:54
【问题描述】:

我正在尝试使用 HTTPBuilder 类将 XML 数据发布到 URL。目前我有:

def http = new HTTPBuilder('http://m4m:aghae7eihuph@m4m.fetchapp.com/api/orders/create')
http.request(POST, XML) {
body = {
        element1 {
            subelement 'value'
            subsubelement {
                key 'value2'
            }
        }
    }           

    response.success = { /* handle success*/ }
    response.failure = { resp, xml -> /* handle failure */ }
}

经过检查,我发现该请求确实以 XML 作为正文。不过,我有 3 个问题。第一个是,它省略了经典的 xml 行:

<?xml version="1.0" encoding="UTF-8"?>

必须在正文顶部,其次内容类型也未设置为:

application/xml

最后,对于XML中的一些元素我需要设置属性,例如:

<element1 type="something">...</element1>

但我不知道如何以上述格式执行此操作。有谁知道怎么做?或者也许是另一种方式?

【问题讨论】:

    标签: xml groovy httpbuilder


    【解决方案1】:
    1. 要添加 XML 声明行,请在标记开头插入 mkp.xmlDeclaration()
    2. ContentType.XML 作为第二个参数传递给请求会将Content-Type 标头设置为application/xml。我不明白为什么这对您不起作用,但您可以尝试改用 application/xml 字符串。
    3. 要设置元素的属性,请在标记生成器中使用以下语法:element1(type: 'something') { ... }

    这是一个例子:

    @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.2')
    import groovyx.net.http.*
    
    new HTTPBuilder('http://localhost:8080/').request(Method.POST, ContentType.XML) {
        body = { 
            mkp.xmlDeclaration()
            element(attr: 'value') {
                foo { 
                    bar()
                } 
            }
        }
    }
    

    生成的 HTTP 请求如下所示:

    POST / HTTP/1.1
    Accept: application/xml, text/xml, application/xhtml+xml, application/atom+xml
    Content-Length: 71
    Content-Type: application/xml
    Host: localhost:8080
    Connection: Keep-Alive
    Accept-Encoding: gzip,deflate
    
    <?xml version='1.0'?>
    <element attr='value'><foo><bar/></foo></element>
    

    【讨论】:

    • 如何打印您的请求?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 2015-10-11
    • 1970-01-01
    相关资源
    最近更新 更多