如何从詹金斯工作流程调用 REST [英] How to call REST from jenkins workflow

查看:13
本文介绍了如何从詹金斯工作流程调用 REST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从(groovy)Jenkins 工作流脚本调用 REST API.我可以执行sh 'curl -X POST ...'" - 它可以工作,但是将请求构建为 curl 命令很麻烦,并且处理响应变得复杂.我更喜欢使用原生 Groovy HTTP 客户端在 groovy 中编程——我应该从哪个开始?由于脚本在 Jenkins 中运行,因此需要将所有需要的依赖 jar 复制到 Jenkins 上的 groovy 安装中,因此轻量级将不胜感激.

I wonder how to call REST API from a (groovy) Jenkins workflow script. I can execute "sh 'curl -X POST ...'" - it works, but building the request as a curl command is cumbersome and processing the response gets complicated. I'd prefer a native Groovy HTTP Client to program in groovy - which one should I start with? As the script is run in Jenkins, there is the step of copying all needed dependency jars to the groovy installation on Jenkins, so something light-weight would be appreciated.

推荐答案

无需导入任何包的原生 Groovy 代码:

Native Groovy Code without importing any packages:

// GET
def get = new URL("https://httpbin.org/get").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if(getRC.equals(200)) {
    println(get.getInputStream().getText());
}


// POST
def post = new URL("https://httpbin.org/post").openConnection();
def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(200)) {
    println(post.getInputStream().getText());
}

这篇关于如何从詹金斯工作流程调用 REST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆