8

I need to create a Groovy post build script in Jenkins and I need to make a request without using any 3rd party libraries as those can't be referenced from Jenkins.

I tried something like this:

def connection = new URL( "https://query.yahooapis.com/v1/public/yql?q=" +
    URLEncoder.encode(
            "select wind from weather.forecast where woeid in " + "(select woeid from geo.places(1) where text='chicago, il')",
            'UTF-8' ) )
    .openConnection() as HttpURLConnection

// set some headers
connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
connection.setRequestProperty( 'Accept', 'application/json' )

// get the response code - automatically sends the request
println connection.responseCode + ": " + connection.inputStream.text

but I also need to pass a JSON in the POST request and I'm not sure how I can do that. Any suggestion appreciated.

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
George Cimpoies
  • 884
  • 2
  • 14
  • 26

1 Answers1

14

Executing POST request is pretty similar to a GET one, for example:

import groovy.json.JsonSlurper

// POST example
try {
    def body = '{"id": 120}'
    def http = new URL("http://localhost:8080/your/target/url").openConnection() as HttpURLConnection
    http.setRequestMethod('POST')
    http.setDoOutput(true)
    http.setRequestProperty("Accept", 'application/json')
    http.setRequestProperty("Content-Type", 'application/json')

    http.outputStream.write(body.getBytes("UTF-8"))
    http.connect()

    def response = [:]    

    if (http.responseCode == 200) {
        response = new JsonSlurper().parseText(http.inputStream.getText('UTF-8'))
    } else {
        response = new JsonSlurper().parseText(http.errorStream.getText('UTF-8'))
    }

    println "response: ${response}"

} catch (Exception e) {
    // handle exception, e.g. Host unreachable, timeout etc.
}

There are two main differences comparing to GET request example:

  1. You have to set HTTP method to POST

    http.setRequestMethod('POST')
    
  2. You write your POST body to outputStream:

    http.outputStream.write(body.getBytes("UTF-8"))
    

    where body might be a JSON represented as string:

    def body = '{"id": 120}'
    

Eventually it's good practice to check what HTTP status code returned: in case of e.g. HTTP 200 OK you will get your response from inputStream while in case of any error like 404, 500 etc. you will get your error response body from errorStream.

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131