使用Groovy HTTPBuilder POST XML数据

Nic*_*men 3 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 {
                key 'value2'
            }
        }
    }           

    response.success = { /* handle success*/ }
    response.failure = { resp, xml -> /* handle failure */ }
}
Run Code Online (Sandbox Code Playgroud)

经过检查,我发现请求确实以XML作为正文.我有3个问题.首先,它省略了经典的xml行:

<?xml version="1.0" encoding="UTF-8"?>
Run Code Online (Sandbox Code Playgroud)

必须在主体的顶部,其次内容类型不设置为:

application/xml
Run Code Online (Sandbox Code Playgroud)

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

<element1 type="something">...</element1>
Run Code Online (Sandbox Code Playgroud)

但我不知道如何以上述格式执行此操作.有谁有想法怎么样?或者可能是另一种方式?

ata*_*lor 5

  1. mkp.xmlDeclaration()在标记的开头添加XML声明行插入.
  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()
            } 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

生成的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>
Run Code Online (Sandbox Code Playgroud)

  • 你如何打印出你的要求? (2认同)