Brad Lee
Brad Lee

Reputation: 649

How to post JSON in Groovy with standard libraries?

What's the easiest way to post JSON to a URL in groovy using only the standard libraries? (ie, without using HttpClient or HttpClientBuilder)

This is a script I'd rather not have to link in lots of other libraries to.

Upvotes: 0

Views: 1960

Answers (1)

Brad Lee
Brad Lee

Reputation: 649

def con = "http://endpointUrl".toURL().openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.outputStream.withWriter { writer ->
  writer << jsonString
}

String response = con.inputStream.withReader { Reader reader -> reader.text }

Upvotes: 1

Related Questions