为什么我无法在jenkins共享库中使用URL,HttpUrlConnection?

时间:2019-11-21 15:41:42

标签: java jenkins groovy jenkins-pipeline jenkins-groovy

我有一个简单的共享库,可以执行http GET。 这些文件存储在vars目录中: simpleHttpGet.groovy

String call(String rawUrl){
    new URL(rawUrl).text
}

httpGet.groovy

String call(String rawUrl){
    URL url = new URL(rawUrl)
    HttpURLConnection connection = url.openConnection()
    connection.setRequestMethod("GET")
    connection.setConnectTimeout(1000)
    connection.setDoInput(true)
    def text = null
    try {
        echo 'trying to connect'
        connection.connect()
        echo 'connected'
        def stream = connection.getInputStream()
        echo "stream $stream"
        text = stream.text
    } finally {
        echo 'disconnected'
        connection.disconnect()
    }
    echo text
    return text
}

当我在管道中使用simpleHttpGet.groovy和httpGet.groovy时,第一个返回null,第二个返回null InputStream。为什么不起作用? 有完整的管道和执行结果。

@Library('simple-http-get') _
pipeline {
    agent any

    options {
        timestamps()
    }

    stages {
        stage('Test') {
            steps {
                script {
                    echo 'curl'
                    def curlResponse = sh(script: 'curl -X GET https://google.com', returnStdout: true)
                    echo curlResponse
                    echo 'simpleHttpGet'
                    def simpleResponse = simpleHttpGet('https://google.com')
                    echo simpleResponse
                    echo 'httpGet'
                    def httpGetResponse = httpGet("https://google.com")
                    echo httpGetResponse
                }
            }
        }
    }
}
[Pipeline] {
[Pipeline] timestamps
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
curl
[Pipeline] sh
+ curl -X GET https://google.com
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100   220  100   220    0     0    820      0 --:--:-- --:--:-- --:--:--   820
100   220  100   220    0     0    820      0 --:--:-- --:--:-- --:--:--   817
[Pipeline] echo
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.com/">here</A>.
</BODY></HTML>

[Pipeline] echo
simpleHttpGet
[Pipeline] echo
null
[Pipeline] echo
httpGet
[Pipeline] echo
trying to connect
[Pipeline] echo
connected
[Pipeline] echo
stream null
[Pipeline] echo
disconnected
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // timestamps
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.NullPointerException: Cannot get property 'text' on null object
    at org.codehaus.groovy.runtime.NullObject.getProperty(NullObject.java:60)
...

0 个答案:

没有答案