如何在Jenkinsfile中从curl获取响应代码

5
在Jenkinsfile中,我使用以下方式调用curl命令:
sh "curl -X POST -i -u admin:admin https://[myhost]"

我得到的输出如下所示:
...
HTTP/1.1 204 No Content
Server: Apache-Coyote/1.1
...

我希望根据上述调用的响应代码执行不同的操作,但是我该如何仅将响应代码/回复存储在变量中?
3个回答

7
通过使用参数-w %{http_code}(来自使用curl获取HTTP状态码), 您可以轻松获取HTTP响应代码:
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")
}


1
将响应放入变量中:
```html

将响应放入变量中:

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

然后使用正则表达式提取状态码。
Pattern pattern = Pattern.compile("(\\d{3})");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
  matcher.group(1);
}

0

给定答案和其他文档的帮助下,我得出了以下解决方案:

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";
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接