Reading — step 1 of 5
Learn
~2 min readSpread, Collections Deep, HTTP
Groovy makes HTTP and JSON unusually pleasant — once you know the patterns.
Quick HTTP GET
import groovy.json.JsonSlurper
def url = "https://api.github.com/repos/torvalds/linux"
def json = new JsonSlurper().parseText(new URL(url).text)
println json.name
println json.stargazers_count
The .text property of a URL makes the GET. JsonSlurper parses.
POST and other methods
import groovy.json.JsonOutput
def payload = JsonOutput.toJson([title: "hello", body: "world"])
def conn = new URL("https://example.com/api/posts").openConnection()
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "application/json")
conn.setDoOutput(true)
conn.outputStream.withWriter { w -> w.write(payload) }
def response = conn.inputStream.text
println response
Verbose. For real HTTP work in Groovy, use libraries:
- HttpBuilder-NG — fluent DSL
- OkHttp (Java library, used directly)
- RESTEasy / Resttassured for testing
// HttpBuilder-NG style:
import static groovyx.net.http.HttpBuilder.configure
def result = configure {
request.uri = 'https://api.example.com'
}.get {
request.uri.path = '/users/42'
response.parser('application/json') { config, fromServer ->
new JsonSlurper().parse(fromServer.inputStream)
}
}
JSON conversion
Object → JSON:
import groovy.json.JsonOutput
def data = [name: "Ada", scores: [80, 92, 75]]
def jsonStr = JsonOutput.toJson(data)
def pretty = JsonOutput.prettyPrint(jsonStr)
JSON → Map/List:
import groovy.json.JsonSlurper
def parsed = new JsonSlurper().parseText('{"name":"Ada","scores":[80,92,75]}')
parsed.name // "Ada"
parsed.scores[0] // 80
Groovy's parseText returns Maps and Lists — the most natural representation.
YAML, XML
- YAML:
org.yaml.snakeyamlis the standard - XML:
XmlSlurperfor namespace-aware parsing,XmlBuilderfor generating
def xml = new XmlSlurper().parseText('''
<root>
<user id="1">Ada</user>
<user id="2">Bob</user>
</root>
''')
xml.user.each { u -> println "$u.@id: $u" }
Authentication
def url = new URL("https://api.example.com/private")
def auth = "Basic " + Base64.encoder.encodeToString("user:pass".bytes)
def conn = url.openConnection()
conn.setRequestProperty("Authorization", auth)
println conn.text
Error handling
Non-2xx HTTP responses throw IOException (the connection's input stream is closed). Wrap in try/catch:
try {
def text = url.text
process(text)
} catch (FileNotFoundException e) {
// 404
} catch (IOException e) {
// network error or 5xx
}
In Judge0 sandboxes, network access is usually disabled — these patterns work in real environments.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…