Jenkins的Groovy脚本:执行没有第三方库的HTTP请求

Geo*_*ies 5 rest groovy http jenkins

我需要在Jenkins中创建一个Groovy post构建脚本,我需要在不使用任何第三方库的情况下发出请求,因为这些库不能从Jenkins引用.

我试过这样的事情:

def connection = new URL( "https://query.yahooapis.com/v1/public/yql?q=" +
    URLEncoder.encode(
            "select wind from weather.forecast where woeid in " + "(select woeid from geo.places(1) where text='chicago, il')",
            'UTF-8' ) )
    .openConnection() as HttpURLConnection

// set some headers
connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
connection.setRequestProperty( 'Accept', 'application/json' )

// get the response code - automatically sends the request
println connection.responseCode + ": " + connection.inputStream.text
Run Code Online (Sandbox Code Playgroud)

但我还需要在POST请求中传递JSON,我不知道如何做到这一点.任何建议表示赞赏.

Szy*_*iak 11

执行POST请求非常类似于GET,例如:

import groovy.json.JsonSlurper

// POST example
try {
    def body = '{"id": 120}'
    def http = new URL("http://localhost:8080/your/target/url").openConnection() as HttpURLConnection
    http.setRequestMethod('POST')
    http.setDoOutput(true)
    http.setRequestProperty("Accept", 'application/json')
    http.setRequestProperty("Content-Type", 'application/json')

    http.outputStream.write(body.getBytes("UTF-8"))
    http.connect()

    def response = [:]    

    if (http.responseCode == 200) {
        response = new JsonSlurper().parseText(http.inputStream.getText('UTF-8'))
    } else {
        response = new JsonSlurper().parseText(http.errorStream.getText('UTF-8'))
    }

    println "response: ${response}"

} catch (Exception e) {
    // handle exception, e.g. Host unreachable, timeout etc.
}
Run Code Online (Sandbox Code Playgroud)

与GET请求示例相比,有两个主要区别:

  1. 您必须将HTTP方法设置为POST

    http.setRequestMethod('POST')
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您将POST主体编写为outputStream:

    http.outputStream.write(body.getBytes("UTF-8"))
    
    Run Code Online (Sandbox Code Playgroud)

    其中body可能是表示为字符串的JSON:

    def body = '{"id": 120}'
    
    Run Code Online (Sandbox Code Playgroud)

最后,它是很好的做法,以检查HTTP状态代码返回了什么:在例如情况下HTTP 200 OK,你会从你的反应inputStream,而在像404的任何错误,500等的情况下,你将得到你的错误响应体errorStream.