[英]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请求示例相比,有两个主要区别:
You have to set HTTP method to POST 您必须将HTTP方法设置为POST
http.setRequestMethod('POST')
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.