在Jenkins中经常会与其他服务活着组建有通信,因此掌握编httpRequest
时很有必要的,我们在编写自定义的工具时,需要对httpRequest有一个整体上的认识,他和我们通常意义上的使用方法有很多共同点,但同时也有些差别,如果不了解这些,将会走很多弯路,下面将分别讲述
在Jenkins中的编写自定义函数,需要掌握的语言是groovy,因为shared-lib是使用groovy脚本实现的,你可以理解为java的shell版本,也就是命令式编程。下面我们用java语言作为对比来理解它。
共同点:
- 请求类型一致,都包含
POST
,PUT
,GET
,DELETE
- 都可以直接使用java语法来编程
差别:
- groovy中的headers声明为customHeaders,对应到java语法上的headers
- groovy语法无需显式调用execute方法请求
- 调用接口的方式不同
下面列举出四种常用的例子说明
- POST请求:
def response = httpRequest contentType: 'APPLICATION_FORM',
httpMode: "POST",
customHeaders: [
[name: "Authorization", value: "Basic xskjasdjkf="]
],
requestBody: "key=key1&value=value1&key2=value",
url: ''
println response.status
println response.content
- PUT请求
def response = httpRequest contentType: 'APPLICATION_JSON',
httpMode: "PUT",
customHeaders: [
[name: "TOKEN", value: "B456skjasdjkf="]
],
url: ''
println response.status
println response.content
- GET请求
def response = httpRequest contentType: 'APPLICATION_JSON',
httpMode: "GET",
customHeaders: [
[name: "TOKEN", value: "B456skjasdjkf="]
],
url: ''
println response.status
println response.content
- DELETE请求
def response = httpRequest contentType: 'APPLICATION_JSON',
httpMode: "DELETE",
customHeaders: [
[name: "TOKEN", value: "B456skjasdjkf="]
],
url: ''
println response.status
println response.content