POST XML data with Groovy HTTPBuilder

一世执手 提交于 2019-12-23 17:25:18

问题


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:


  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>


来源:https://stackoverflow.com/questions/11017126/post-xml-data-with-groovy-httpbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!