从Jenkins迁移至GitHub Actions:Groovy脚本curl请求执行失败
问题排查与解决方案
问题原因
你用execute()执行curl命令时,返回的是java.lang.Process对象,而非直接的HTTP响应字符串。contains()是String类的方法,直接在Process对象上调用会触发MissingMethodException,因为Process类没有这个方法。
解决方案
要获取curl的响应内容,需要读取Process的输入流;同时为避免进程阻塞,还要处理错误流,最后等待进程执行完成。
方法1:正确处理Process对象获取响应
// 构造curl命令 def curlCmd = "curl -X POST https://your-config-api.com/apps/products -d 'config-data'" def process = curlCmd.execute() // 读取标准输出(响应内容) def response = process.inputStream.text // 读取错误输出(防止进程因未读取错误流而挂起) def errorLog = process.errorStream.text // 等待进程执行完毕 process.waitFor() // 现在可以用contains()判断响应内容或直接检查退出码 if (response.contains("200 OK")) { println "配置执行成功" } else { println "配置失败,响应内容:${response}\n错误日志:${errorLog}" }
方法2:用Groovy原生HTTP客户端替代curl(更推荐)
避免调用外部进程的麻烦,直接用Groovy自带的HTTP工具类:
def configUrl = new URL("https://your-config-api.com/apps/products") def connection = configUrl.openConnection() connection.setRequestMethod("POST") connection.setDoOutput(true) connection.setRequestProperty("Content-Type", "application/json") // 写入请求体 def requestBody = '{"key": "value"}' connection.outputStream.write(requestBody.getBytes()) // 获取响应码和内容 def responseCode = connection.responseCode def responseContent = connection.inputStream.text if (responseCode == 200) { println "配置成功" } else { println "配置失败,响应码:${responseCode},内容:${responseContent}" }
这种方式无需依赖系统curl命令,跨环境兼容性更好,也更容易捕获和处理HTTP请求细节。
内容的提问来源于stack exchange,提问作者Reddy Rohit
相关产品推荐
相关产品推荐

