簡體   English   中英

Jenkins的Groovy腳本:執行沒有第三方庫的HTTP請求

[英]Groovy script for Jenkins: execute HTTP request without 3rd party libraries

我需要在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,我不知道如何做到這一點。 任何建議表示贊賞。

執行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}' 

最終檢查返回的HTTP狀態代碼是一個好習慣:在例如HTTP 200 OK情況下,您將從inputStream獲得響應,而在出現任何錯誤(如404,500等)時,您將從errorStream獲取錯誤響應正文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM