如何在Jenkins DSL中返回Httprequest的body



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

我已经设置了logResponseBody: true,但我没有在控制台日志中获得任何身体输出。

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()}"
                }
            }
        }
    }
}

在此示例中,我们将连接到Open JSON API(https://dog.ceo/api/breeds/list/all/all(,并且我们使用echo方法显示两件事:http status status http status和此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

希望它有帮助。

最新更新