【问题标题】:HTTPBuilder set requestBody on GET methodHTTPBuilder 在 GET 方法上设置 requestBody
【发布时间】:2012-03-28 23:06:26
【问题描述】:

使用 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?

【问题讨论】:

    标签: groovy get request httpbuilder


    【解决方案1】:

    简短回答:不。

    长答案:除了实际创建请求时,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 不能有主体,但它说如果请求语义不允许,则不能提供它,并且接收此类请求的服务器应忽略它。

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

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

    【讨论】:

      猜你喜欢
      • 2015-11-10
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多