Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy script for Jenkins: execute HTTP request without 3rd party libraries

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.

like image 231
George Cimpoies Avatar asked Feb 07 '18 13:02

George Cimpoies


People also ask

How do you call REST API from Groovy?

Get the Places connection to execute the HTTP GET request on this resource and pass the text entered in the EmployeeAddress RTP as the value for the input query parameter. The Places connection object is a communication link between the Groovy script and the Google Places REST API resource.

How do I run a Jenkins Groovy script?

Usage. To create Groovy-based project, add new free-style project and select "Execute Groovy script" in the Build section, select previously configured Groovy installation and then type your command, or specify your script file name. In the second case path taken is relatively from the project workspace directory.

Can Jenkins call a REST API?

Most tools today support Restful API calls as an integration point. Making Restful API calls from the Jenkins Groovy Pipeline script can be difficult since the version embedded in Jenkins can be limited in its functionality. A quick and dirty way to make Restful API calls uses a script, curl, or wget.


1 Answers

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.

like image 87
Szymon Stepniak Avatar answered Nov 15 '22 07:11

Szymon Stepniak