So I'm trying to make a put request with HttpURLConnection in a groovy script running inside Jenkins. I have successfully made get and post calls with url-encoded-data, but the put request with a JSON body is not working. I've tried many solutions with no success.
Here is my current code with debugging prints:
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
jenkins.println("Enter try block...")
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
jenkins.println("Open connection...")
urlConnection.setRequestMethod("PUT");
// urlConnection.setRequestProperty("Content-Type", "application/json")
urlConnection.setRequestProperty("Authorization", "Bearer " + token)
urlConnection.setRequestProperty("Accept", "application/json")
urlConnection.setDoOutput(false);
urlConnection.setDoInput(true);
urlConnection.connect();
jenkins.println("Connect...")
OutputStream writer = urlConnection.getOutputStream()
// OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
jenkins.println("Created writer...")
byte[] outputInBytes = data.getBytes("UTF-8")
writer.write(outputInBytes)
// writer.write(data)
jenkins.println("wrote data...")
writer.flush()
jenkins.println("flushed...")
writer.close()
jenkins.println("writer closed...")
jenkins.println("------- Print response codes and message -------")
jenkins.println(urlConnection.getResponseCode())
jenkins.println(urlConnection.getResponseMessage())
jenkins.println("Begin input stream...")
stream = urlConnection.getInputStream()
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
jenkins.println(JsonHelper.parse(result))
return JsonHelper.parse(result)
The Jenkins output is:
Incoming json is: {
"name": "Signature-Verification",
"owningTeam": 281,
"customFields": [
{
"id": 2,
"value": "My team is awesome"
},
{
"id": 3,
"value": "apitesttothemoon"
}
]
}
[Pipeline] echo
Enter try block...
[Pipeline] echo
Open connection...
[Pipeline] echo
Connect...
[Pipeline] echo
null
[Pipeline] End of Pipeline
Finished: SUCCESS
Based on the logs I know it's failing at the creation of the writer. I just don't know why. The writer creates and works fine for the url-encoded post requests, but not the put.
Any insight is appreciated. I've put several hours into this and don't know where to go next.