http - 使用 Groovy 重写 curl http 请求
问题描述
这是我需要重写以在 groovy 中使用的测试 HTTP 请求:
curl 'https://api-dev.test.ru/uaa/oauth/token' -H 'Authorization: Basic 1234567=' -H 'Content-Type: application/x-www-form- urlencoded' -H 'Accept: application/json, text/plain, */*' --data 'grant_type=password' --data-urlencode 'username=theLogin' --data-urlencode 'password=thePassword'
这是我重写它的方式:
def httpRequest = [path : 'https://api-dev.test.ru/uaa/oauth/token',
headers : ['Authorization: Basic 1234567='
'Content-Type': 'application/x-www-form-urlencoded',
'Accept' : 'application/json, text/plain, */*'],
data : ['grant_type=password'],
data_urlencode: ['username=theLogin',
'password=thePassword']
]
这似乎不正确,因为测试应用程序不适用于该请求。我是否正确地重写了请求。如果我没有,我的错误在哪里?
解决方案
您应该使用Http Builder。您的代码如下所示:
def result = HttpBuilder,configure {
request.uri = 'https://api-dev.test.ru/uaa/oauth/token'
request.contentType = 'application/x-www-form-urlencoded'
request.headers.Accept = 'application/json, text/plain, */*'
}.post {
request.auth.basic 'admin', 'myp@$$w0rd'
request.uri.query = [ grant_type:'password' ]
request.body = [username:'theLogin', password:'thePassword']
}