我需要压缩一个字符串来减小web服务响应的大小。我在SharpZipLib示例中看到了单元测试,但并不是我真正需要的示例。
在下面的代码中,ZipOutputStream的构造函数返回异常:"No open entry“
byte[] buffer = Encoding.UTF8.GetBytes(SomeLargeString);
Debug.WriteLine(string.Format("Original byes of string: {0}", buffer.Length));
MemoryStream ms = new MemoryStream();
using (ZipOutputStream zipStream = new ZipOutputStream(ms))
{
zipStream.Write(buffer, 0, buffer.Length);
Debug.WriteLine(string.Format("Compressed byes: {0}", ms.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);
string compressedString = Convert.ToBase64String (gzBuffer);我哪里偏离正轨了?我是不是把事情搞得太复杂了?
发布于 2012-03-23 05:06:57
您确定将数据转换为Base64后,数据会变得那么小吗?这将显著地膨胀二进制数据(zip)。您不能使用HTTP压缩在传输级别解决这个问题吗?
这里有一篇完整源代码的文章,展示了如何做往返的zip/unzip。
http://paultechguy.blogspot.com/2008/09/zip-xml-in-memory-for-web-service.html
发布于 2014-12-31 22:56:39
对于来自Silverlight的web服务通信压缩数据,我使用以下代码片段:
private byte[] zipText(string text)
{
if (text == null)
return null;
using(Stream memOutput = new MemoryStream())
{
using (GZipOutputStream zipOut = new GZipOutputStream(memOutput))
{
using (StreamWriter writer = new StreamWriter(zipOut))
{
writer.Write(text);
writer.Flush();
zipOut.Finish();
byte[] bytes = new byte[memOutput.Length];
memOutput.Seek(0, SeekOrigin.Begin);
memOutput.Read(bytes, 0, bytes.Length);
return bytes;
}
}
}
}
private string unzipText(byte[] bytes)
{
if (bytes == null)
return null;
using(Stream memInput = new MemoryStream(bytes))
using(GZipInputStream zipInput = new GZipInputStream(memInput))
using(StreamReader reader = new StreamReader(zipInput))
{
string text = reader.ReadToEnd();
return text;
}
}Zip compression
我的案例是json数据的压缩。根据我的观察,在某些情况下,大约95Kb的文本数据被压缩到1.5Kb。因此,即使数据将被序列化到64位,无论如何都可以很好地节省通信量。
发布了我的答案,这可能是为了节省一些时间。
发布于 2012-03-23 05:23:18
你的代码有几个问题:
使用streams时,
ms.ToArray();
中找到一个好的示例
https://stackoverflow.com/questions/9830428
复制相似问题