Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST XML data with Groovy HTTPBuilder

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:[email protected]/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?

like image 666
Nico Huysamen Avatar asked May 14 '26 02:05

Nico Huysamen


1 Answers

  1. To add the XML declaration line insert mkp.xmlDeclaration() at the beginning of your markup.
  2. Passing ContentType.XML as the second parameter to request sets the Content-Type header to application/xml. I can't see why that isn't working for you, but you can try using a string of application/xml instead.
  3. 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>
like image 92
ataylor Avatar answered May 15 '26 19:05

ataylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!