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

时间:2018-02-07 13:33:59

标签: rest http jenkins groovy

我需要在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

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

1 个答案:

答案 0 :(得分:8)

执行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.
}

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

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

    http.setRequestMethod('POST')
    
  2. 您将POST主体写入outputStream

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

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

    def body = '{"id": 120}'
    
  3. 最终检查返回的HTTP状态代码是一种很好的做法:例如, HTTP 200 OK您将收到来自inputStream的回复,如果出现404,500等错误,您将从errorStream获得错误回复正文。