3

I am trying gradle for the first time.

I want to call some REST API in a gradle script and validate some responses I receive back.

Current system configurations include Java 1.7, Gradle 2.4 running on a Oracle Linux 6.5

My REST API :

API => POST localhost/Assign

JSON Input :

{"user":"dummyuser"}

JSON Output :

{
  "jobMessageDetails": "dummyuser has been assigned to dummymachine",
  "jobStatusDetails": "Success",
  "jobType": "assign",
  "machineName": "dummymachine",
  "time": "2015/6/8 @ 14:47:42",
  "userName": "dummyuser"
}

I am able to test my APIs using POSTMAN from another machine. I do it like this : POST hostname??:5500/Assign JSON_INPUT using POSTMAN. They work correctly.

What I want to do :

  • I want to call this API from a Gradle script.
  • I want to parse the JSON_OUTPUT I receive.
  • I want to read and print the "jobStatusDetails" & "machineName" from the response I receive.

PS : I am very new to Gradle, I would appreciate a full working code.

I have looked at the following links - link1 link2. None of them helped me.

Community
  • 1
  • 1
sudhishkr
  • 3,318
  • 5
  • 33
  • 55

1 Answers1

1

You can use the URLConnection API.

Post method example:

task demo {
    doLast {
        def body = [user: "dummyUser"]
        def req = new URL('https://hostname/Assign').openConnection()
        req.setRequestMethod("POST")
        req.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
        req.setDoOutput(true)
        req.getOutputStream().write(JsonOutput.toJson(body).getBytes("UTF-8"))
        logger.quiet "Status code: ${req.getResponseCode()}" // HTTP request done on first read
        def resp = new JsonSlurper().parseText(req.getInputStream().getText())
        logger.quiet "Response: ${resp}"
    }
}

For parsing you can use JsonSlurper

turkogluc
  • 148
  • 1
  • 10