如何用Jenkins中的httpRequest封裝http請求

在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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章