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

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

我需要在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,我不知道如何做到这一点。任何建议表示赞赏。

rest http jenkins groovy
1个回答
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主体写到qazxsw poi: qazxsw poi 其中qazxsw poi可能是一个表示为字符串的JSON: outputStream

最终,检查返回的HTTP状态代码是一种好习惯:例如, http.outputStream.write(body.getBytes("UTF-8")) 你将得到body的回复,如果有任何错误,如404,500等,你将从def body = '{"id": 120}' 得到你的错误回复正文。

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