5

使用 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\"}]}"

为了便于阅读,这里是合理格式的 JSON:

{"stuff":"yes",
"listThing":[1,2,3],
"listObjects":[{"one":"thing"},{"two":"thing2"}]}

通常-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
}

哪个有效,但如果我更改.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

有没有办法使用 HTTPBuilder 发送带有请求正文的 GET?

4

1 回答 1

2

简短的回答:没有。

长答案:除了实际创建请求时,HTTPBuilder 不允许您在任何时候为请求设置 HTTP 方法。参数也在创建时由一个闭包设置,该闭包检查请求的类型,如果请求不是 HttpEntityEnclosureRequest 类型,则抛出该异常。

您可以在此处查看源代码:https ://fisheye.codehaus.org/browse/gmod/httpbuilder/trunk/src/main/java/groovyx/net/http/HTTPBuilder.java?hb=true

附带说明一下,HTTP 1.1 规范并没有直接说 GET 不能有正文,但它说如果请求语义不允许,则不能提供它,并且服务器接收这样的requests 应该忽略它。

由于大多数人都习惯了这种约定,我建议坚持它,并且在发送 GET 请求时不要让您的服务实际使用正文。

另请参阅此问题:HTTP GET with request body

于 2012-04-05T09:27:57.787 回答