Last active
January 16, 2025 23:36
-
-
Save thorntonrose/e67aa6c23d593c9d5bb6 to your computer and use it in GitHub Desktop.
Simple Groovy REST client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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