È possibile usufruire di Groovy caratteristiche come con(), miglioramenti URLConnection, e getter/setter semplificati:
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.
})
nota, il POST inizierà quando si tenta di leggere un valore dalla HttpURLConnection, come ad esempio responseCode
, inputStream.text
o getHeaderField('...')
.
Per riepilogare le risposte sottostanti 'j = new groovy.json.JsonSlurper(). ParseText (nuovo URL (" https://httpbin.org/get ") .getText())' then 'println j.headers ["User-Agent"] ' – MarkHu
È anche possibile eseguire il checkout di una (ri) versione aggiornata della libreria HttpBuilder - https://http-builder-ng.github.io/http-builder-ng/ – cjstehno
Se si utilizza' @ Grab' rende http-builder abbastanza indolore da usare: '@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.7')' –