简体   繁体   English

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

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

I need to create a Groovy post build script in Jenkins and I need to make a request without using any 3rd party libraries as those can't be referenced from Jenkins. 我需要在Jenkins中创建一个Groovy post构建脚本,我需要在不使用任何第三方库的情况下发出请求,因为这些库不能从Jenkins引用。

I tried something like this: 我试过这样的事情:

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

but I also need to pass a JSON in the POST request and I'm not sure how I can do that. 但我还需要在POST请求中传递JSON,我不知道如何做到这一点。 Any suggestion appreciated. 任何建议表示赞赏。

Executing POST request is pretty similar to a GET one, for example: 执行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.
}

There are two main differences comparing to GET request example: 与GET请求示例相比,有两个主要区别:

  1. You have to set HTTP method to POST 您必须将HTTP方法设置为POST

     http.setRequestMethod('POST') 
  2. You write your POST body to outputStream : 您将POST主体写入outputStream

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

    where body might be a JSON represented as string: body可能是表示为字符串的JSON:

     def body = '{"id": 120}' 

Eventually it's good practice to check what HTTP status code returned: in case of eg HTTP 200 OK you will get your response from inputStream while in case of any error like 404, 500 etc. you will get your error response body from errorStream . 最终检查返回的HTTP状态代码是一个好习惯:在例如HTTP 200 OK情况下,您将从inputStream获得响应,而在出现任何错误(如404,500等)时,您将从errorStream获取错误响应正文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Gradle 脚本要在没有任何第 3 方插件的情况下调用 REST Web 服务,有任何指示吗? - Gradle Script To call a REST Web service without any 3rd party plugins, any pointers? 对第三方API的CORS和HTTP请求之间的区别 - Difference between CORS and HTTP requests to a 3rd party API 使用SSL向第三方API发出POST请求失败:“Access-Control-Allow-Origin不允许使用原始http:// localhost:5000”。 - POST request with SSL to 3rd party API, failing: “Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin.” 在 Groovy (Jenkins) 中循环执行 HTTP Post - Execute HTTP Post in a loop in Groovy (Jenkins) 如果第三方API身份验证失败,我的API应返回哪些HTTP错误代码? - What HTTP error codes should my API return if a 3rd party API auth fails? 当第三方资源无法使用时的REST HTTP响应代码 - REST HTTP Response Code when 3rd party ressource became unaviable 我是否通过多个用户访问Google Apps脚本中的第三方API重新发明了轮子? - Did I reinvent the wheel with multiple user access to 3rd party API within Google Apps Script? 通过身份验证访问第三方服务 - Accessing 3rd Party Services With Authentication 适用于第三方客户(AAA)的REST API - rest api for 3rd party customers (AAA) Wordpress,消费第三方 REST Api - Wordpress, consume 3rd party REST Api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM