HTTP POST in GROOVY



我拼命想把这个python代码翻译成groovy,但我找不到合适的解决方案。

如果有人能帮我一点,那就太好了

#! /usr/bin/env python3
# coding: utf-8
import requests
url = "http://localhost:8088/mockServiceSoapBinding"
xml = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sam="http://www.soapui.org/sample/">
<soapenv:Header/>
<soapenv:Body>
<sam:login>
<username>Login</username>
<password>Login123</password>
</sam:login>
</soapenv:Body>
</soapenv:Envelope>'''
headers = {'content-type': 'text/xml;charset=UTF-8', 'Accept-Encoding': 'gzip,deflate'}
r1 = requests.post(url, data=xml, headers=headers, auth=('user', 'pass'))
print(r1.text)

从Groovy进行HTTPPOST调用可以通过初始化URL连接来完成。

下面是一个工作示例:

url = 'http://localhost:8088/mockServiceSoapBinding'
def username = 'user'
def password = 'pass'
xml = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sam="http://www.soapui.org/sample/">
<soapenv:Header/>
<soapenv:Body>
<sam:login>
<username>Login</username>
<password>Login123</password>
</sam:login>
</soapenv:Body>
</soapenv:Envelope>'''
def connection = new URL(url).openConnection()
connection.setRequestMethod('POST')
// set headers
connection.setRequestProperty('Content-Type', 'text/xml;charset=UTF-8')
connection.setRequestProperty('Accept-Encoding', 'gzip,deflate')
if (username && password) {
String userCredentials = username + ':' + password
String basicAuth = 'Basic ' + Base64.getEncoder().encode(userCredentials.getBytes())
connection.setRequestProperty('Authorization', basicAuth)
}
connection.doOutput = true
connection.outputStream.write(xml.getBytes('UTF-8'))
println "XX: connect"
connection.connect()
println "XX: get content"
def text = connection.content.text
println(text)

最新更新