问题
I am trying to POST XML data to a URL using the HTTPBuilder class. At the moment I have:
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 */ }
}
and upon inspection I see that the request does get made with the XML as the body. I have 3 issues with this though. The first is, it omits the classic xml line:
<?xml version="1.0" encoding="UTF-8"?>
which has to go at the top of the body, and secondly also the content type is not set to:
application/xml
Then lastly, for some of the elements in the XML I need to set attributes, for example:
<element1 type="something">...</element1>
but I have no idea how to do this in the format above. Does anyone have an idea how? Or maybe an alternative way?
回答1:
- To add the XML declaration line insert mkp.xmlDeclaration() at the beginning of your markup.
- Passing ContentType.XML as the second parameter to request sets the
Content-Type
header toapplication/xml
. I can't see why that isn't working for you, but you can try using a string ofapplication/xml
instead. - To set attributes on an element, use this syntax in the markup builder:
element1(type: 'something') { ... }
Here's an example:
@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()
}
}
}
}
The resulting HTTP request looks like this:
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>
来源:https://stackoverflow.com/questions/11017126/post-xml-data-with-groovy-httpbuilder