为什么GZip算法的结果在Android和.Net中不相同?
我在android中的代码:
public static String compressString(String str) {
String str1 = null;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
BufferedOutputStream dest = null;
byte b[] = str.getBytes();
GZIPOutputStream gz = new GZIPOutputStream(bos,b.length);
gz.write(b,b.length);
bos.close();
gz.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
byte b1[] = bos.toByteArray();
return Base64.encode(b1);
}
我在.Net WebService中的代码:
public static string compressString(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms,CompressionMode.Compress,true))
{
zip.Write(buffer,buffer.Length);
}
ms.Position = 0;
MemoryStream outStream = new MemoryStream();
byte[] compressed = new byte[ms.Length];
ms.Read(compressed,compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed,gzBuffer,4,compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length),4);
return Convert.ToBase64String(gzBuffer);
}
在android中:
compressString("hello"); -> "H4sIAAAAAAAAAMtIzcnJBwCGphA2BQAAAA=="
在.Net:
compressString("hello"); -> "BQAAAB+LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee++997o7nU4n99//P1xmZAFs9s5K2smeIYCqyB8/fnwfPyLmeVlW/w+GphA2BQAAAA=="
有趣的是,当我在android中使用Decompress方法解压缩.Net compressString方法的结果时,它正确返回原始字符串,但是当我解压缩android compressedString方法的结果时出错.
Android解压缩方法:
public static String Decompress(String zipText) throws IOException {
int size = 0;
byte[] gzipBuff = Base64.decode(zipText);
ByteArrayInputStream memstream = new ByteArrayInputStream(gzipBuff,gzipBuff.length - 4);
GZIPInputStream gzin = new GZIPInputStream(memstream);
final int buffSize = 8192;
byte[] tempBuffer = new byte[buffSize];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((size = gzin.read(tempBuffer,buffSize)) != -1) {
baos.write(tempBuffer,size);
}
byte[] buffer = baos.toByteArray();
baos.close();
return new String(buffer,"UTF-8");
}