Groovy built-in REST/HTTP client?

前端 未结 7 1002
迷失自我
迷失自我 2020-11-28 19:51

I heard that Groovy has a built-in REST/HTTP client. The only library I can find is HttpBuilder, is this it?

Basically I\'m looking for a way to do

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 20:17

    You can take advantage of Groovy features like with(), improvements to URLConnection, and simplified getters/setters:

    GET:

    String getResult = new URL('http://mytestsite/bloop').text
    

    POST:

    String postResult
    ((HttpURLConnection)new URL('http://mytestsite/bloop').openConnection()).with({
        requestMethod = 'POST'
        doOutput = true
        setRequestProperty('Content-Type', '...') // Set your content type.
        outputStream.withPrintWriter({printWriter ->
            printWriter.write('...') // Your post data. Could also use withWriter() if you don't want to write a String.
        })
        // Can check 'responseCode' here if you like.
        postResult = inputStream.text // Using 'inputStream.text' because 'content' will throw an exception when empty.
    })
    

    Note, the POST will start when you try to read a value from the HttpURLConnection, such as responseCode, inputStream.text, or getHeaderField('...').

提交回复
热议问题