我需要在 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 请求示例相比有两个主要区别:
您必须将 HTTP 方法设置为 POST
http.setRequestMethod('POST')
您将 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/