问题
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?
回答1:
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")
}
回答2:
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);
}
回答3:
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";
}
}
}
来源:https://stackoverflow.com/questions/48688664/how-to-get-response-code-from-curl-in-a-jenkinsfile