如何从 Jenkins Groovy 脚本中执行 HTTP POST 请求? [英] How can I perform HTTP POST requests from within a Jenkins Groovy script?

查看:55
本文介绍了如何从 Jenkins Groovy 脚本中执行 HTTP POST 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够在我们的 Jenkins Pipeline 构建期间创建简单的 HTTP POST 请求.但是我不能使用简单的 curl sh 脚本,因为我需要它在 Windows 和 Linux 节点上工作,如果可以避免的话,我不希望在节点上强制安装更多工具.

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.

我们正在使用的 Pipeline 插件中使用的 Groovy 库应该非常适合这项任务.Groovy 有一个可用于执行简单 POST 的扩展,称为 http-builder,但我一生都无法弄清楚如何在 Jenkins 的 Groovy 安装中使用它.

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.

如果我尝试在 Pipeline 脚本中使用 Grapes Grab 来使用它,我会收到错误消息,在这里看到.

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')
)

Groovy Jenkins 使用的捆绑版本可能不支持 Grapes Grab.是否可以简单地下载 http-builder 及其依赖项并将其添加到输出到节点的 Jenkins Groovy 安装中?

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?

推荐答案

也许我遗漏了一些东西,但为什么不直接使用 jenkins 类路径中已经存在的标准 java 库呢?

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")

这篇关于如何从 Jenkins Groovy 脚本中执行 HTTP POST 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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