Groovy built-in REST/HTTP client?
Native Groovy GET and POST
// GET
def get = new URL("https://httpbin.org/get").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if (getRC.equals(200)) {
println(get.getInputStream().getText());
}
// POST
def post = new URL("https://httpbin.org/post").openConnection();
def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if (postRC.equals(200)) {
println(post.getInputStream().getText());
}
If your needs are simple and you want to avoid adding additional dependencies you may be able to use the getText()
methods that Groovy adds to the java.net.URL
class:
new URL("http://stackoverflow.com").getText()
// or
new URL("http://stackoverflow.com")
.getText(connectTimeout: 5000,
readTimeout: 10000,
useCaches: true,
allowUserInteraction: false,
requestProperties: ['Connection': 'close'])
If you are expecting binary data back there is also similar functionality provided by the newInputStream()
methods.