I have built a string on an Android device, and I need to compress it and send it via Bluetooth Low Energy to a NodeJS application, where it needs to be unzipped.
On the Android/Java side, I compress it using GZIP and then Base64 encode it before sending it as follows:
public static String compress(String str) throws IOException {
byte[] blockcopy = ByteBuffer
.allocate(4)
.order(java.nio.ByteOrder.LITTLE_ENDIAN)
.putInt(str.length())
.array();
ByteArrayOutputStream os = new ByteArrayOutputStream(str.length());
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(str.getBytes());
gos.close();
os.close();
byte[] compressed = new byte[4 + os.toByteArray().length];
System.arraycopy(blockcopy, 0, compressed, 0, 4);
System.arraycopy(os.toByteArray(), 0, compressed, 4,
os.toByteArray().length);
return Base64.encodeToString(compressed, Base64.DEFAULT);
}
On the NodeJS side, I receive it, decode the Base64 and then attempt to unzip it as follows using the zlib
library:
var buf = Buffer.from(raw, 'base64');
var data = zlib.gunzipSync(buf);
I have tested the Bluetooth communication on its own, and regular, unzipped data is collected completely fine. I have also tested sending the raw data uncompressed but encoded in Base64, and that also decodes and works fine. However, when attempting to decompress, I get the following error from the zlib
library:
{ Error: incorrect header check
at Gunzip.zlibOnError (zlib.js:153:15)
at Gunzip._processChunk (zlib.js:411:30)
at zlibBufferSync (zlib.js:144:38)
at Object.gunzipSync (zlib.js:590:14)
...
errno: -3, code: 'Z_DATA_ERROR' }
What am I doing wrong, and how can I go about fixing this?