Jenkins 2中http-builder-ng Groovy模块的兼容性

48次阅读
没有评论

问题描述

有人在Jenkins pipeline中使用过http-builder-ng Groovy模块吗?当我在桌面上运行相同的源代码时,无论是什么类型的请求/URL,它总是返回null对象。
以下是调试输出:

groovyx.net.http.UriBuilder$Basic@4bc2413c scheme=http port=-1 host=api.open-notify.org path=/astros.json query=[:] fragment=null userInfo=null parent=groovyx.net.http.UriBuilder$ThreadSafe@69c6847a useRawValues=null

旧版本的这个模块由groovy.codehouse开发,它工作正常,但它没有我需要的一些方法。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

我建议尽量避免导入模块,你可以使用内置功能来实现相同的结果。另外要注意“In-process Script Approval”。
以下是使用内置功能实现相同结果的示例代码:

// 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())
}

你也可以重写请求方法:

conn.setRequestProperty("X-HTTP-Method-Override", "PATCH")
conn.setRequestMethod("POST")

方案2

请注意以下操作注意版本差异及修改前做好备份。
另一种方法是使用脚本或工具来控制容器的运行顺序。你可以使用docker run命令来手动控制容器的启动顺序,或者使用一些第三方工具来管理容器的依赖关系。

示例:

以下是一个简单的bash脚本示例,可以在容器A启动后启动容器B:

#!/bin/bash
# 启动容器A
docker run -d --name container_a your_image_a
# 等待容器A完全启动
while ! docker exec container_a echo "Container A is ready"; do
  sleep 1
done
# 启动容器B
docker run -d --name container_b your_image_b

在这个示例中,我们首先使用docker run命令启动容器A,并将其命名为container_a。然后,使用一个循环来等待容器A完全启动(这里是通过在容器内运行echo命令来测试)。一旦容器A就绪,我们再使用docker run命令启动容器B,并将其命名为container_b

正文完