I'm trying to 1. download a ZIP file in Groovy and 2. unzip the contents of that file. The code that exists currently is as follows:
try{
URL url = new URL(testUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization","Bearer "+testPassword);
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write("");
osw.flush();
osw.close();
os.close();
conn.getInputStream();
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output2;
StringBuffer response2 = new StringBuffer();
while ((output2 = bufferReader.readLine()) != null) {
response2.append(output2);
println(output2.toString());
}
println("Output:-" + output2.toString());
bufferReader.close();
// printing result from response
println("Response:-" + response2.toString());
} catch (Exception e) {
println("Error:"+e.getMessage());
println("Error:"+e.printStackTrace());
}
(variables are defined earlier in the code.)
When I run this on a valid URL containing a ZIP file, I get the following output:
Response:-P�;Uv�4J -p��A���5�� ���K\G�"�)�荚���%nM%��Qf��Z�$���m����PK�;Uv��4J -payload.jsonPK[UJ
I can tell from reading the response that it's reading in the file somewhat-correctly, hence the Payload...json
string in the content, but what I don't understand is how to convert that response (which looks like base64 to me) into a usable/human-readable string. I've tried a number of solutions found in other answers - for example, putting this following function in the code:
def unzip(String compressed){
def inflaterStream = new GZIPInputStream(new ByteArrayInputStream(compressed.decodeBase64()))
def uncompressedStr = inflaterStream.getText('UTF-8')
return uncompressedStr
}
and then calling it via unzip(theLargeResponse)
. When I try that, I get Error:bad character in base64 value
error - but I can't determine where the bad character is coming in or how to mitigate it. I've also tried the answer suggested here:
https://stackoverflow.com/a/45854656/5266746
But that gives me compilation errors when I put the string above in the PUT BASE 64ENCODED GZIPPED STRING HERE
spot. I'm wondering if I'm even going about this the right way. Does anyone see anything that might stick out or make this make a bit more sense to me?
Thanks!
zip is not gzip. gzip is not zip.
You are reading in a zip file, indicated by the first two bytes "PK". You are then trying to decode it as a gzip file, which it isn't. You need save the thing and unzip it with unzip.