Question

Using cURL I can send a GET request with a body. Example:

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

Here is the JSON in a reasonable format for legibility's sake:

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

Normally -d will tell cURL to send a POST but I have confirmed that the -X GET is overriding that and it is sending GET. Is it possible to replicate this with HTTPBuilder?

I have done:

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
}

Which works, but if I change .post to .get I get the error:

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

Is there a way to send a GET with a request body using HTTPBuilder?

Was it helpful?

Solution

Short answer: No.

Long answer: The HTTPBuilder doesn't let you set the HTTP method for a request at any time other than when actually creating a request. Parameters are also set at creating by a closure which checks the type of request and throws that exception if the request is not of type HttpEntityEnclosingRequest.

You can check the source code here: https://fisheye.codehaus.org/browse/gmod/httpbuilder/trunk/src/main/java/groovyx/net/http/HTTPBuilder.java?hb=true

On a side note, the HTTP 1.1 spec doesn't say outright that a GET can't have a body, but it says that if a request semantics doesn't allow one, then it must not be provided, and that servers receiving such requests should ignore it.

Since most people are used to that convention, I would suggest sticking with it, and not having your service actually make use of the body when sending a GET request.

See also this question: HTTP GET with request body

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top