时间:2021-07-01 10:21:17 帮助过:5人阅读
http://blog.csdn.net/michaell_zhang/article/details/5979883
C#客户端访问PHP SOAP WebService,当传输大量文本数据时,可以通过压缩减少网络传输。
C#在System.IO.Compression命名空间下提供了两个类GZipStream 类和DeflateStream类来进行数据的压缩和解压缩。经本人实验,在C#下使用GZipStream压缩的字符串在PHP下使用gzuncompress函数无法解压缩,有人说可以使用gzdecode解开,但本人的PHP不支持gzdecode函数,但有gzencode函数(why?原因未明,据说是PHP的BUG,可能到PHP6才提供此函数)。
C#下使用DeflateStream类压缩文本后,可以在PHP下用gzinflate解压缩。示例代码如下:
客户端C#(在头4个字节增加了原文本的长度,方便在C#中解压缩,对于在PHP端解压缩这个没有用处):
public static string Compress(string text) { byte[] buffer = Encoding.UTF8.GetBytes(text); MemoryStream ms = new MemoryStream(); using (DeflateStream zip = new DeflateStream(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); }
?服务端PHP:
?
function Decompress($strSource){ $strTemp = base64_decode($strSource); $strTemp = substr($strTemp, 4); return gzinflate($strTemp);}
?支持中文,编码为UTF8.
?
http://blog.csdn.net/allsharps/article/details/7357328
////// 简单的压缩 /// public static class CompressHelper { ////// 压缩字符串 /// /// ///public static byte[] CompressString(string str) { return CompressBytes(Encoding.UTF8.GetBytes(str)); } /// /// 压缩二进制 /// /// ///public static byte[] CompressBytes(byte[] str) { var ms = new MemoryStream(str) {Position = 0}; var outms = new MemoryStream(); using (var deflateStream = new DeflateStream(outms, CompressionMode.Compress, true)) { var buf = new byte[1024]; int len; while ((len = ms.Read(buf, 0, buf.Length)) > 0) deflateStream.Write(buf, 0, len); } return outms.ToArray(); } /// /// 解压字符串 /// /// ///public static string DecompressString(byte[] str) { return Encoding.UTF8.GetString(DecompressBytes(str)); } /// /// 解压二进制 /// /// ///public static byte[] DecompressBytes(byte[] str) { var ms = new MemoryStream(str) {Position = 0}; var outms = new MemoryStream(); using (var deflateStream = new DeflateStream(ms, CompressionMode.Decompress, true)) { var buf = new byte[1024]; int len; while ((len = deflateStream.Read(buf, 0, buf.Length)) > 0) outms.Write(buf, 0, len); } return outms.ToArray(); } }
?
?