How to call REST from jenkins workflow

前端 未结 5 1934
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-24 06:23

I wonder how to call REST API from a (groovy) Jenkins workflow script. I can execute \"sh \'curl -X POST ...\'\" - it works, but building the request as a curl command is cu

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 06:55

    Native Groovy Code without importing any packages:

    // 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());
    }
    

提交回复
热议问题