我正在尝试使用 HTTPBuilder 类将 XML 数据发布到 URL。目前我有:
def http = new HTTPBuilder('http://m4m:[email protected] /cdn-cgi/l/email-protection/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 声明行插入mkp.xmlDeclaration() http://groovy.codehaus.org/api/groovy/xml/MarkupBuilderHelper.html#xmlDeclaration%28java.util.Map%29在标记的开头。
- Passing ContentType.XML http://groovy.codehaus.org/modules/http-builder/apidocs/groovyx/net/http/ContentType.html#XML作为请求的第二个参数设置
Content-Type
标头至application/xml
。我不明白为什么这对你不起作用,但你可以尝试使用一串application/xml
反而。
- 要设置元素的属性,请在标记生成器中使用以下语法:
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)