Skip to content

Instantly share code, notes, and snippets.

@imoutsatsos
Created April 29, 2023 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imoutsatsos/def117e0da2ce30c75d472686a1a1de2 to your computer and use it in GitHub Desktop.
Save imoutsatsos/def117e0da2ce30c75d472686a1a1de2 to your computer and use it in GitHub Desktop.
/*
Suggested by ChatGPT
Here's an example Groovy script that uses the `HttpURLConnection` class
to connect to a web service, send a JSON payload via HTTP POST, and record the response:
*/
import java.net.HttpURLConnection
import java.net.URL
// Define the URL of the web service
def url = new URL("http://example.com/myservice")
// Define the JSON payload to send
def payload = '{"DatabaseID":"BooHoo","Paths":["Path1","Path2"]}'
// Create an HttpURLConnection object
def connection = url.openConnection() as HttpURLConnection
// Set the request method to POST
connection.requestMethod = "POST"
// Set the content type to JSON
connection.setRequestProperty("Content-Type", "application/json")
// Enable output and disable input
connection.doOutput = true
connection.doInput = false
// Write the payload to the request body
def outputStream = connection.outputStream
outputStream.write(payload.getBytes("UTF-8"))
outputStream.flush()
outputStream.close()
// Read the response from the server
def responseCode = connection.responseCode
def inputStream = responseCode < HttpURLConnection.HTTP_BAD_REQUEST ? connection.inputStream : connection.errorStream
def response = new StringBuffer()
def reader = new BufferedReader(new InputStreamReader(inputStream))
def line = null
while ((line = reader.readLine()) != null) {
response.append(line)
}
reader.close()
inputStream.close()
connection.disconnect()
// Print the response to the console
println("Response code: ${responseCode}")
println("Response body: ${response.toString()}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment