Created
April 29, 2023 12:56
-
-
Save imoutsatsos/def117e0da2ce30c75d472686a1a1de2 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
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