Jenkinsfile:使用groovy调用GitHub API

问题描述 投票:0回答:1

我正在尝试向 Jenkins 中的 GitHub 拉取请求添加评论。我正在使用共享库并有这个方法:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
import groovyx.net.http.RESTClient

def call() {
    withCredentials([string(credentialsId: 'github-api-token', variable: 'GITHUB_ACCESS_TOKEN')]) {
        def apiUrl = "https://{GITHUB_URL}/api/v3/repos/{ORG}/{REPO}/issues/1/comments"
        
        def client = new groovyx.net.http.RESTClient(apiUrl)
        client.headers['Authorization'] = "token ${GITHUB_ACCESS_TOKEN}"
        client.headers['Content-Type'] = 'application/vnd.github+json'
        def response = client.post(body: [body: "comment via jenkins method"] as JSON)
        
        if (response.status == 201) {
            println "Comment added successfully to Pull Request"
        } else {
            println "Failed to add comment to Pull Request. Status code: ${response.status}, Response: ${response.data}"
        }
    }
}

但是,我收到错误:

unable to resolve class JSON  09:56:46   @ line 12, column 42. 09:56:46      response = client.post(body: [body: "co

删除

as JSON
会导致出现此错误:
java.lang.IllegalArgumentException: No encoder found for request content type */*

有人可以给我任何提示我做错了什么吗?

groovy jenkins-pipeline github-api jenkins-groovy
1个回答
0
投票

要回答您的直接问题,您需要指定

requestContentType
参数,而不是尝试强制转换
body
参数:

def response = client.post(body: [body: "comment via jenkins method"],
                           requestContentType: groovyx.net.http.ContentType.JSON)

它就在 docs 中。

但是为什么你想要

@Grab
第三方库(不推荐)而不是可能已经安装的东西? github-apiokhttp-api 在 Jenkins 实例上都非常常见,并且使用与 http-builder 模块相同的构建器模式。

© www.soinside.com 2019 - 2024. All rights reserved.