Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I perform HTTP POST requests from within a Jenkins Groovy script?

Tags:

I need to be able to create simple HTTP POST request during our Jenkins Pipeline builds. However I cannot use a simple curl sh script as I need it to work on Windows and Linux nodes, and I don't wish to enforce more tooling installs on nodes if I can avoid it.

The Groovy library in use in the Pipeline plugin we're using should be perfect for this task. There is an extension available for Groovy to perform simple POSTs called http-builder, but I can't for the life of me work out how to make use of it in Jenkins' Groovy installation.

If I try to use Grapes Grab to use it within a Pipeline script I get an error failing to do so, as seen here.

@Grapes(     @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1') ) 

Maybe Grapes Grab isn't supported in the bundled version of Groovy Jenkins uses. Is it possible to simply download and add http-builder and its dependencies to the Jenkins Groovy installation that goes out to the nodes?

like image 741
S.Richmond Avatar asked Mar 20 '16 15:03

S.Richmond


People also ask

What happens when you send POST HTTP request to Jenkins URL?

This plugin sends a HTTP/HTTPS request to a user specified URL. The request is made as a job execution in Jenkins and depending of the HTTP response the job could be marked as failed (configurable). For example, responses such as 404 and 500 could make the job fail.

How do you call a Groovy script from Jenkins?

In Jenkinsfile, simply use load step to load the Groovy script. After the Groovy script is loaded, the functions insides can be used where it can be referenced, as shown above.


2 Answers

For the Jenkin's Pipeline I would recommend installing the "HTTP-Request" plugin

It is nicely integrated in groovy so you can use it like this:

def response = httpRequest "http://httpbin.org/response-headers?param1=${param1}" 
like image 50
Alfredo MS Avatar answered Sep 21 '22 06:09

Alfredo MS


Perhaps I'm missing something, but why not just use standard java libraries that are already on the jenkins classpath?

import java.io.BufferedReader import java.io.InputStreamReader import java.io.OutputStreamWriter import java.net.URL import java.net.URLConnection  def sendPostRequest(urlString, paramString) {     def url = new URL(urlString)     def conn = url.openConnection()     conn.setDoOutput(true)     def writer = new OutputStreamWriter(conn.getOutputStream())      writer.write(paramString)     writer.flush()     String line     def reader = new BufferedReader(new     InputStreamReader(conn.getInputStream()))     while ((line = reader.readLine()) != null) {       println line     }     writer.close()     reader.close() }  sendPostRequest("http://www.something.com", "param1=abc&param2=def") 
like image 43
TheEllis Avatar answered Sep 19 '22 06:09

TheEllis