我需要编写一个类似于此 cURL 的脚本
curl -X 'POST' 'url/authenticate' -H 'accept: */*' -H 'Content-Type: multipart/form-data' -F 'Username=user_name' -F 'Password=pass_word'
我有这个,但请求响应代码 400 表示密码字段是必需的,用户名字段是必需的
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.Method
def http = new HTTPBuilder('url/authenticate')
def body = [
"Username": 'user_name',
"Password": 'pass_word'
]
http.request(Method.POST, ContentType.URLENC) {
headers.'Accept' = '*/*'
body = body
response.success = { resp, reader ->
log.warn("Response Status: ${resp.statusLine}")
log.warn("Response Data: ${reader}")
}
response.failure = { resp, reader ->
log.warn("Error Response Status: ${resp.statusLine}")
log.warn("Error Response Data: ${reader}")
}
}
如何在此脚本中正确传递表单字段?
附注Postman 的 POST 请求工作正常,在请求正文中提供此表单字段
您可以使用 PAT(个人访问令牌)代替基本身份验证:
def oauthToken = 'Your Token'
try {
def connection = new URL(url).openConnection()
connection.requestMethod = 'GET'
connection.setRequestProperty("Authorization", "Bearer " + oauthToken)
connection.setRequestProperty("Content-Type", "application/json")
connection.connect()
...
...