u123
u123

Reputation: 16267

How to get response code from curl in a jenkinsfile

In a jenkinsfile I call curl with:

sh "curl -X POST -i -u admin:admin https://[myhost]"

and I get output like this:

...
HTTP/1.1 204 No Content
Server: Apache-Coyote/1.1
...

I would like to take different actions based on the response code from the above call but how do I store only the response code/reply in a variable?

Upvotes: 5

Views: 16077

Answers (3)

LE GALL Benoît
LE GALL Benoît

Reputation: 7568

By using the parameter -w %{http_code}(from Use HTTP status codes from curl)

you can easily get the HTTP response code:

int status = sh(script: "curl -sLI -w '%{http_code}' $url -o /dev/null", returnStdout: true)

if (status != 200 && status != 201) {
    error("Returned status code = $status when calling $url")
}

Upvotes: 7

Hans Wouters
Hans Wouters

Reputation: 628

With the help of the given answer and other docs, I came to the following solution:

steps {
  // I already had 'steps', below was added.
  script {
    response = sh(
      returnStdout: true, 
      script: "curl -X POST ..."
    );
    // The response is now in the variable 'response'

    // Then you can regex to read the status. 
    // For some reasen, the regex needs to match the entire result found.
    // (?s) was necessary for the multiline response.
    def finder = (response =~ /(?s).*HTTP/1.1 (\d{3}).*/);
    if (finder) {
      echo 'Status ' + finder.group(1);
    } else {
      echo "no match";
    }
  }
}

Upvotes: 0

bp2010
bp2010

Reputation: 2462

To put the response into a variable:

def response = sh returnStdout: true, script: 'curl -X POST -i -u admin:admin https://[myhost]'

Then use regex to extract the status code.

Pattern pattern = Pattern.compile("(\\d{3})");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
  matcher.group(1);
}

Upvotes: 1

Related Questions