Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yanhua365/cbdc2512ab5d75003ab4d80e399af774 to your computer and use it in GitHub Desktop.
Save yanhua365/cbdc2512ab5d75003ab4d80e399af774 to your computer and use it in GitHub Desktop.
Groovy script to make HTTP request using Java standard library.
URL url = new URL(urlTarget);
HttpURLConnection connection;
method = "GET" // POST, PUT, ...
data = "" // for GET, otherwise e..g JSON
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
// connection.addRequestProperty("Accept", "application/json")
// connection.addRequestProperty("Content-Type", "application/json")
connection.connect();
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (data);
wr.flush ();
wr.close ();
println "responseCode: " + connection.getResponseCode()
InputStream response = connection.getInputStream();
String content = new java.util.Scanner(response).useDelimiter("\\A").next();
println(content);
return content;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment