如何在Jenkins DSL中返回httpRequest的主体?

时间:2018-02-12 14:11:25

标签: jenkins groovy

我有一个步骤使用httpRequest步骤成功调用远程URL但是,我不知道如何使用返回的正文。

我设置了logResponseBody: true但是我没有在控制台日志中获得正文的任何​​输出。

1 个答案:

答案 0 :(得分:6)

httpRequest插件返回一个响应对象,该对象公开像例如

这样的方法
  • Stirng getContent() - 回复正文为String
  • int getStatus() - HTTP状态代码

您可以使用JsonSlurper类来解析对JSON对象的响应(如果您从请求中获取的响应是JSON类型)。考虑以下示例性管道:

import groovy.json.JsonSlurper

pipeline {
    agent any 
    stages {
        stage('Build') { 
            steps {
                script {
                    def response = httpRequest 'https://dog.ceo/api/breeds/list/all'
                    def json = new JsonSlurper().parseText(response.content)

                    echo "Status: ${response.status}"

                    echo "Dogs: ${json.message.keySet()}"
                }
            }
        }
    }
}

在此示例中,我们将连接到打开的JSON API(https://dog.ceo/api/breeds/list/all),并使用echo方法显示两个方面:HTTP状态和此JSON响应中所有狗的列表。如果您在Jenkins中运行此管道,您将在控制台日志中看到类似的内容:

[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/test-pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] script
[Pipeline] {
[Pipeline] httpRequest
HttpMethod: GET
URL: https://dog.ceo/api/breeds/list/all
Sending request to url: https://dog.ceo/api/breeds/list/all
Response Code: HTTP/1.1 200 OK
Success code from [100‥399]
[Pipeline] echo
Status: 200
[Pipeline] echo
Dogs: [affenpinscher, african, airedale, akita, appenzeller, basenji, beagle, bluetick, borzoi, bouvier, boxer, brabancon, briard, bulldog, bullterrier, cairn, chihuahua, chow, clumber, collie, coonhound, corgi, dachshund, dane, deerhound, dhole, dingo, doberman, elkhound, entlebucher, eskimo, germanshepherd, greyhound, groenendael, hound, husky, keeshond, kelpie, komondor, kuvasz, labrador, leonberg, lhasa, malamute, malinois, maltese, mastiff, mexicanhairless, mountain, newfoundland, otterhound, papillon, pekinese, pembroke, pinscher, pointer, pomeranian, poodle, pug, pyrenees, redbone, retriever, ridgeback, rottweiler, saluki, samoyed, schipperke, schnauzer, setter, sheepdog, shiba, shihtzu, spaniel, springer, stbernard, terrier, vizsla, weimaraner, whippet, wolfhound]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

希望它有所帮助。