Mik*_*key 5 groovy get request httpbuilder
使用cURL我可以发送一个正文的GET请求.例:
curl -i -X GET http://localhost:8081/myproject/someController/l2json -H "content-type: application/json" -d "{\"stuff\":\"yes\",\"listThing\":[1,2,3],\"listObjects\":[{\"one\":\"thing\"},{\"two\":\"thing2\"}]}"
Run Code Online (Sandbox Code Playgroud)
为了清晰起见,这是合理格式的JSON:
{"stuff":"yes",
"listThing":[1,2,3],
"listObjects":[{"one":"thing"},{"two":"thing2"}]}
Run Code Online (Sandbox Code Playgroud)
通常-d会告诉cURL发送一个POST,但我已经确认它-X GET正在覆盖它并且它正在发送GET.是否可以使用HTTPBuilder复制它?
我已经做好了:
def http = new HTTPBuilder( 'http://localhost:8081/' )
http.post(path:'/myproject/myController/l2json', body:jsonMe, requestContentType:ContentType.JSON) { resp ->
println "Tweet response status: ${resp.statusLine}"
assert resp.statusLine.statusCode == 200
}
Run Code Online (Sandbox Code Playgroud)
哪个有效,但如果我.post改为.get我得到错误:
Cannot set a request body for a GET method. Stacktrace follows:
Message: Cannot set a request body for a GET method
Line | Method
->> 1144 | setBody in groovyx.net.http.HTTPBuilder$RequestConfigDelegate
Run Code Online (Sandbox Code Playgroud)
有没有办法使用HTTPBuilder发送请求正文的GET?
小智 2
简短回答:不。
长答案:HTTPBuilder 不允许您在实际创建请求之外的任何时间设置请求的 HTTP 方法。参数也在创建时通过闭包进行设置,该闭包检查请求的类型,如果请求不是 HttpEntityEnlookingRequest 类型,则抛出该异常。
附带说明一下,HTTP 1.1 规范并没有直接规定 GET 不能有主体,但它说如果请求语义不允许有主体,则不得提供主体,并且服务器接收此类主体请求应该忽略它。
由于大多数人都习惯了该约定,因此我建议坚持使用它,并且不要让您的服务在发送 GET 请求时实际使用正文。
另请参阅这个问题:HTTP GET with request body
| 归档时间: |
|
| 查看次数: |
2234 次 |
| 最近记录: |