【发布时间】:2017-09-30 01:50:02
【问题描述】:
我有以下代码来连接到 REST API 服务、进行身份验证、检索会话 ID,然后通过会话 ID 发出进一步的请求以进行身份验证。初始请求有效,我在响应中得到 HTTP 200 OK 加上会话 ID,但是当我尝试发出第二个请求时,在标头中传递会话 ID,我得到 p>
捕获:groovyx.net.http.HttpResponseException: Bad Request
我知道使用类和 try/catch 等可以更好地编写脚本。我仍在学习 java 和 groovy,所以我首先尝试在同一个类中做所有事情。
非常感谢任何帮助。
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.URIBuilder
import static groovyx.net.http.Method.POST
import static groovyx.net.http.ContentType.*
def url = 'https://1.1.1.1/web_api/'
def uri = new URIBuilder(url)
String CHKPsid
uri.path = 'login'
def http = new HTTPBuilder(uri)
http.ignoreSSLIssues()
http.request(POST,JSON ) { req ->
headers.'Content-Type' = 'application/json'
body = [
"user":"username",
"password":"password"
]
response.success = { resp, json ->
println (json)
CHKPsid = (json.sid)
println "POST Success: ${resp.statusLine}"
}
}
uri.path = 'show-changes'
http.request(POST,JSON ) { req ->
headers.'Content-Type' = 'application/json'
headers.'X-chkp-sid' = '${CHKPsid}'
body = [
"from-date" : "2017-02-01T08:20:50",
"to-date" : "2017-10-21"
]
response.success = { resp, json ->
println (json)
println "POST Success: ${resp.statusLine}"
}
}
【问题讨论】:
-
400 Bad Request表示您的请求不正确。尝试先读取服务器响应,看看你正在执行的请求有什么问题(REST API 应该返回一个描述错误的 JSON 对象)。 -
感谢@SzymonStepniak。失败响应如下[code:generic_err_invalid_syntax, message:Login request message processing failed] POST Failure: HTTP/1.1 400 Bad Request。我怀疑错误的代码是我尝试将会话 ID 分配变量(CHKPsid)的值作为 X-chkp-sid 传递到请求标头中。这看起来正确吗?
标签: groovy httpbuilder