2016-01-08 64 views
8

我想知道如何從(groovy)Jenkins工作流腳本中調用REST API。我可以執行「sh'curl -X POST ...'」 - 它可以工作,但將請求作爲curl命令構建起來很麻煩,處理響應變得複雜。我更喜歡本地的Groovy HTTP客戶端在groovy中進行編程 - 我應該從哪一個開始?由於腳本在Jenkins中運行,所以需要將所有需要的依賴關係jar複製到Jenkins上的groovy安裝中,因此輕量級的東西將值得讚賞。如何從jenkins工作流程調用REST

+0

你找到了解如何將HTTPBuilder安裝到Jenkin中S' –

+0

S.Richmond將問題中提到的所有缺少的jar複製到Groovy libs文件夾中,但這樣做使Jenkins服務器的配置過於複雜。畢竟,我認爲我堅持捲曲。 –

+0

你介意在jenkins安裝中指出文件夾的存在位置嗎? –

回答

0

您是否嘗試過Groovy的HTTPBuilder類? 例如:

@Grapes(
    @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1') 
) 

import groovyx.net.http.HTTPBuilder 
import static groovyx.net.http.ContentType.* 
import static groovyx.net.http.Method.* 

def http = new HTTPBuilder("http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo") 

http.request(POST, JSON) { req -> 
    body = [] 
    response.success = { resp, reader -> 
     println "$resp.statusLine Respond rec" 

    } 
} 
+3

根據OP的要求,您可以擴展一下如何將HTTPBuilder庫安裝到Jenkins中嗎?它似乎默認情況下不可用。 –

+0

我已經更新了示例以展示如何使用Grapes Grab來拉取相關的HttpBuilder庫,而不需要額外的步驟來包含在Jenkins類路徑中。 – pczeus

+0

我終於開始測試這個,不幸的是它失敗了,並帶有這裏的錯誤:https://gist.github.com/strich/38e472eac507bc73e785 –

1

阻塞主線程I/O調用是不是一個好主意。

當前,建議將I/O操作委託給shell步驟。

另一種需要開發的方式是增加一個新的步驟。順便說一下,有一個an initiative添加了一套通用的步驟來安全地使用流水線腳本,儘管一個完整的REST客戶端擁有自己的插件。

+0

感謝您對pipeline-utility-steps-plugin的鏈接,感興趣。 –

8

我在安裝HTTPBuilder庫時遇到了問題,所以我最終使用了更基本的URL類來創建HttpUrlConnection。

HttpResponse doGetHttpRequest(String requestUrl){  
    URL url = new URL(requestUrl);  
    HttpURLConnection connection = url.openConnection();  

    connection.setRequestMethod("GET");  

    //get the request  
    connection.connect();  

    //parse the response  
    HttpResponse resp = new HttpResponse(connection);  

    if(resp.isFailure()){  
     error("\nGET from URL: $requestUrl\n HTTP Status: $resp.statusCode\n Message: $resp.message\n Response Body: $resp.body");  
    }  

    this.printDebug("Request (GET):\n URL: $requestUrl");  
    this.printDebug("Response:\n HTTP Status: $resp.statusCode\n Message: $resp.message\n Response Body: $resp.body");  

    return resp;  
} 

/**  
* Posts the json content to the given url and ensures a 200 or 201 status on the response.  
* If a negative status is returned, an error will be raised and the pipeline will fail.  
*/  
HttpResponse doPostHttpRequestWithJson(String json, String requestUrl){  
    return doHttpRequestWithJson(json, requestUrl, "POST");  
}  

/**  
* Posts the json content to the given url and ensures a 200 or 201 status on the response.  
* If a negative status is returned, an error will be raised and the pipeline will fail.  
*/  
HttpResponse doPutHttpRequestWithJson(String json, String requestUrl){  
    return doHttpRequestWithJson(json, requestUrl, "PUT");  
} 

/**  
* Post/Put the json content to the given url and ensures a 200 or 201 status on the response.  
* If a negative status is returned, an error will be raised and the pipeline will fail.  
* verb - PUT or POST  
*/  
HttpResponse doHttpRequestWithJson(String json, String requestUrl, String verb){  
    URL url = new URL(requestUrl);  
    HttpURLConnection connection = url.openConnection();  

    connection.setRequestMethod(verb);  
    connection.setRequestProperty("Content-Type", "application/json");  
    connection.doOutput = true;  

    //write the payload to the body of the request  
    def writer = new OutputStreamWriter(connection.outputStream);  
    writer.write(json);  
    writer.flush();  
    writer.close();  

    //post the request  
    connection.connect();  

    //parse the response  
    HttpResponse resp = new HttpResponse(connection);  

    if(resp.isFailure()){  
     error("\n$verb to URL: $requestUrl\n JSON: $json\n HTTP Status: $resp.statusCode\n Message: $resp.message\n Response Body: $resp.body");  
    }  

    this.printDebug("Request ($verb):\n URL: $requestUrl\n JSON: $json");  
    this.printDebug("Response:\n HTTP Status: $resp.statusCode\n Message: $resp.message\n Response Body: $resp.body");  

    return resp;  
} 

class HttpResponse {  

    String body;  
    String message;  
    Integer statusCode;  
    boolean failure = false;  

    public HttpResponse(HttpURLConnection connection){  
     this.statusCode = connection.responseCode;  
     this.message = connection.responseMessage;  

     if(statusCode == 200 || statusCode == 201){  
      this.body = connection.content.text;//this would fail the pipeline if there was a 400  
     }else{  
      this.failure = true;  
      this.body = connection.getErrorStream().text;  
     }  

     connection = null; //set connection to null for good measure, since we are done with it  
    }  
} 

,然後我可以做一個GET的東西,如: HttpResponse resp = doGetHttpRequest("http://some.url");

而且使用的東西與JSON數據的PUT,如: HttpResponse resp = this.doPutHttpRequestWithJson("{\"propA\":\"foo\"}", "http://some.url");

+0

謝謝,這可能是要走的路。我提出了你的答案,一旦我有一些時間來測試它,我會接受它。 –

5

有一個內置在步驟可用的是使用Jenkins HTTP請求插件發出http請求。

插件:https://wiki.jenkins-ci.org/display/JENKINS/HTTP+Request+Plugin

步驟文檔:從插件GitHub的頁面https://jenkins.io/doc/pipeline/steps/http_request/#httprequest-perform-an-http-request-and-return-a-response-object

例子:

def response = httpRequest "http://httpbin.org/response-headers?param1=${param1}" 
println('Status: '+response.status) 
println('Response: '+response.content) 
+0

它支持https嗎?如果是這樣,如何配置證書? @raitisd – Joey

+0

@Van,我假設你不需要在Jenkins端配置任何東西。您只需在網址中使用https即可。你調用的資源必須有ssl設置。 – raitisd

0

本地Groovy代碼而不導入任何軟件包:

// GET 
def get = new URL("https://httpbin.org/get").openConnection(); 
def getRC = get.getResponseCode(); 
println(getRC); 
if(getRC.equals(200)) { 
    println(get.getInputStream().getText()); 
} 


// POST 
def post = new URL("https://httpbin.org/post").openConnection(); 
def message = '{"message":"this is a message"}' 
post.setRequestMethod("POST") 
post.setDoOutput(true) 
post.setRequestProperty("Content-Type", "application/json") 
post.getOutputStream().write(message.getBytes("UTF-8")); 
def postRC = post.getResponseCode(); 
println(postRC); 
if(postRC.equals(200)) { 
    println(post.getInputStream().getText()); 
} 
相關問題