使用Groovy HTTPBuilder发送XML数据的POST请求

3

我正在尝试使用HTTPBuilder类将XML数据以POST方式发送到一个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 */ }
}

经检查,我发现请求确实是以XML作为正文发送的。但我对此有三个问题。第一个问题是它省略了经典的xml行:

<?xml version="1.0" encoding="UTF-8"?>

需要放在文档头部的代码,其次内容类型也未设置为:

application/xml

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

<element1 type="something">...</element1>

但我不知道如何按照上述格式实现这一点。有人知道怎么做吗?或者有其他的方法吗?

1个回答

5
  1. 要在标记的开头插入XML声明行,请插入mkp.xmlDeclaration()
  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()
            } 
        }
    }
}

生成的 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>

2
你如何打印出你的请求? - Eric Francis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接