Skip to content

Instantly share code, notes, and snippets.

@thorntonrose
Last active August 12, 2022 08:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thorntonrose/e67aa6c23d593c9d5bb6 to your computer and use it in GitHub Desktop.
Save thorntonrose/e67aa6c23d593c9d5bb6 to your computer and use it in GitHub Desktop.
Simple Groovy REST client
class RestClient {
def proxy = Proxy.NO_PROXY
def basicAuth
// ???: Bake this into request()?
static def encodePath(path) {
path.replaceAll(" ", "%20")
}
def getContent(String url) {
def (status, content) = get(url)
if (status != 200) { throw new RuntimeException("$status: $content") }
content
}
def get(String url) {
request "GET", url
}
def post(String url, content = null) {
request "POST", url, content
}
def put(String url, content = null) {
request "PUT", url, content
}
def delete(String url) {
request "DELETE", url
}
def request(String method, String url, outContent = null) {
def conn = (HttpURLConnection) new URL(url).openConnection(proxy)
conn.requestMethod = method
conn.doInput = true
conn.doOutput = (outContent != null)
if (basicAuth) { conn.setRequestProperty "Authorization", "Basic " + basicAuth.bytes.encodeBase64().toString() }
conn.connect()
try {
if (outContent != null) { conn.outputStream.withWriter { it.write outContent } }
def status = conn.responseCode
def inContent = (status >= 400 ? conn.errorStream : conn.inputStream)?.text
[ status, inContent ]
} finally {
conn.disconnect()
}
}
static void main(String[] args) {
def (status, content) = new RestClient().get("http://www.google.com")
println "HTTP $status\n$content"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment