rest - Jenkins : execute HTTP request without 3rd party libraries 的 Groovy 脚本

标签 rest http jenkins groovy

我需要在 Jenkins 中创建一个 Groovy 后期构建脚本,并且我需要在不使用任何第 3 方库的情况下发出请求,因为 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 获得错误响应正文。 .

关于rest - Jenkins : execute HTTP request without 3rd party libraries 的 Groovy 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48665187/

相关文章:

api - 构建 API key 和访问 token

java - WebSphere 应用程序服务器/java.lang.ClassCastException

javascript - HTTPS 页面中的 HTTP iFrame 空白

python - 是否可以在不使用 jenkins 上的 "PyAutoGUI"库的情况下使用键盘操作?

networking - 使用 headless jnlp 将从属连接到主控时显示异常

java - 更新时将数据发送到另一台服务器

api - 超媒体API链接遍历与实用性

java - 在 java : Files corrupted 中通过 HTTP post 接收文件

http - OpenID Connect 访问 token 有什么用?

jenkins - Jenkins配置页面中不提供MSBuild插件配置