Any idea why Java's GZIPOutputStream compressed string is different from my .NET's GZIP compressed string?
Java Code:
package com.company;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
String myValue = "<Grid type=\"mailing_activity_demo\"><ReturnFields><DataElement>mailing_id</DataElement></ReturnFields></Grid>";
int length = myValue.length();
byte[] compressionResult = null;
try {
compressionResult = MyUtils.compress(myValue);
} catch (IOException e) {
e.printStackTrace();
}
byte[] headerBytes = ByteBuffer.allocate(4).putInt(length).array();
byte[] fullBytes = new byte[headerBytes.length + compressionResult.length];
System.arraycopy(headerBytes, 0, fullBytes, 0, headerBytes.length);
System.arraycopy(compressionResult, 0, fullBytes, headerBytes.length, compressionResult.length);
String result = Base64.getEncoder().encodeToString(fullBytes);
System.out.println((result));
}
}
package com.company;
import javax.sound.sampled.AudioFormat;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPOutputStream;
public class MyUtils
{
private static Object BitConverter;
public static byte[] compress(String data) throws IOException
{
ByteBuffer buffer = StandardCharsets.UTF_8.encode(data);
System.out.println(buffer.array().length);
System.out.println(data.length());
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
}
The string that I get from above is:
AAAAbB+LCAAAAAAAAP+zcS/KTFEoqSxItVXKTczMycxLj09MLsksyyypjE9Jzc1XsrMJSi0pLcpzy0zNSSm2s3FJLEl0zUnNTc0rsYPpyEyx0UcWt9FH1aMPssUOAKHavIJsAAAA
from the .NET c# code:
public static string CompressData(string data)
{
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] plainBytes = Encoding.UTF8.GetBytes(data);
using (GZipStream zipStream = new GZipStream(memoryStream, CompressionMode.Compress, leaveOpen: true))
{
zipStream.Write(plainBytes, 0, plainBytes.Length);
}
memoryStream.Position = 0;
byte[] compressedBytes = new byte[memoryStream.Length + CompressedMessageHeaderLength];
Buffer.BlockCopy(
BitConverter.GetBytes(plainBytes.Length),
0,
compressedBytes,
0,
CompressedMessageHeaderLength
);
// Add the header, which is the length of the compressed message.
memoryStream.Read(compressedBytes, CompressedMessageHeaderLength, (int)memoryStream.Length);
string compressedXml = Convert.ToBase64String(compressedBytes);
return compressedXml;
}
}
Compressed string:
bAAAAB+LCAAAAAAABACzcS/KTFEoqSxItVXKTczMycxLj09MLsksyyypjE9Jzc1XsrMJSi0pLcpzy0zNSSm2s3FJLEl0zUnNTc0rsYPpyEyx0UcWt9FH1aMPssUOAKHavIJsAAAA
Any idea what am I doing wrong in Java code?