使用Groovy HTTPBuilder发布XML数据

使用Groovy HTTPBuilder发布XML数据,xml,groovy,httpbuilder,Xml,Groovy,Httpbuilder,我试图使用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 {

我试图使用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作为主体的。不过我有三个问题。首先,它省略了经典的xml行:

<?xml version="1.0" encoding="UTF-8"?>
最后,对于XML中的一些元素,我需要设置属性,例如:

<element1 type="something">...</element1>
。。。
但我不知道如何在上面的格式这样做。有人知道怎么做吗?或者是另一种方式

  • 要添加XML声明行,请在标记的开头插入
  • 作为第二个参数传递到请求将
    内容类型
    头设置为
    应用程序/xml
    。我不明白为什么这对您不起作用,但您可以尝试使用字符串
    application/xml
  • 要设置元素的属性,请在标记生成器中使用以下语法:
    element1(键入:'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>
    
    POST/HTTP/1.1
    接受:application/xml、text/xml、application/xhtml+xml、application/atom+xml
    内容长度:71
    内容类型:application/xml
    主机:本地主机:8080
    连接:保持活力
    接受编码:gzip,deflate
    
    如何打印您的请求?
    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>