How to do a POST request with JSON via Groovy?
18,945
Although for a simple GET
you could use plain Groovy:
'https://xxx.xxx.xxx/xapplication/xwebhook/xxxx-xxxx'.toURL().text
However that doesn't give you much flexibility (different http verbs, content-type negociation...etc). Instead I would use HttpBuilder-NG which is a very complete library and it's built having Groovy syntax in mind.
Regarding a working JSON example, the following sends a JSON body in a POST
request and parses back the response, which will be available as a traversable map:
@Grab('io.github.http-builder-ng:http-builder-ng-okhttp:0.14.2')
import static groovy.json.JsonOutput.toJson
import static groovyx.net.http.HttpBuilder.configure
def posts = configure {
request.uri = 'https://jsonplaceholder.typicode.com'
request.uri.path = '/posts'
request.contentType = 'application/json'
request.body = toJson(title: 'food', body: 'bar', userId: 1)
}.post()
assert posts.title == 'foo'
Related videos on Youtube
Author by
Anshul Patel
Updated on May 26, 2022Comments
-
Anshul Patel almost 2 years
I have one REST API, which expects data. We are using following curl command for sending data and header information:
curl -X "POST" "https://xxx.xxx.xxx/xapplication/xwebhook/xxxx-xxxx" -d "Hello, This is data"
What will be the equivalent Groovy Script?
-
tim_yates about 7 yearsHave you tried anything?
-
Anshul Patel about 7 yearsFollowing thread solved my issues stackoverflow.com/questions/25692515/…
-
-
sodastream about 3 yearsThe HttpBuilder-NG seems to be dormant as of October 2020.
-
Filipe Madureira almost 3 years@sodastream 6 months later still dormant.