【发布时间】:2011-08-14 04:33:45
【问题描述】:
为什么 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, 0, 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, 0, buffer.Length);
}
ms.Position = 0;
MemoryStream outStream = new MemoryStream();
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String(gzBuffer);
}
在安卓中:
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, 4,
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, 0, buffSize)) != -1) {
baos.write(tempBuffer, 0, size);
}
byte[] buffer = baos.toByteArray();
baos.close();
return new String(buffer, "UTF-8");
}
我认为 Android compressString 方法有错误。 有人可以帮帮我吗?
【问题讨论】:
-
我解决了 ZipOutputStream 的类似问题stackoverflow.com/a/11154161/1269737
标签: android .net gzip compression