您的位置:首页 > 编程语言 > C#

C# Deflate 压缩与解压缩

2015-07-01 11:36 573 查看
//web Api

        [DeflateCompression]

        [HttpPost]

        public HttpResponseMessage DeflateTest()

        {

            string httpRequestMessage = string.Format("{{\"status\":\"{0}\",\"message\":\"{1}\",\"userInfo\":{2}}}", "12", "Deflate压缩POST测试!", "[]");

            return new HttpResponseMessage { Content = new StringContent(httpRequestMessage) };
        }

//过滤器,写在web Api的类库里

public class DeflateCompressionAttribute : ActionFilterAttribute

    {

        public override void OnActionExecuted(HttpActionExecutedContext actContext)

        {

            var content = actContext.Response.Content;

            var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;

            var zlibbedContent = bytes == null ? new byte[0] :

            CompressionHelper.DeflateByte(bytes);

            actContext.Response.Content = new ByteArrayContent(zlibbedContent);

            actContext.Response.Content.Headers.Remove("Content-Type");

            actContext.Response.Content.Headers.Add("Content-encoding", "deflate");

            //actContext.Response.Content.Headers.Add("Content-Type", "application/json");

            actContext.Response.Content.Headers.Add("Content-Type", "application/json;charset=utf-8");

            base.OnActionExecuted(actContext);

        }

    }

    public class CompressionHelper

    {

        public static byte[] DeflateByte(byte[] str)

        {

            if (str == null)

            {

                return null;

            }

            using (var output = new MemoryStream())

            {

                using (

                  var compressor = new Ionic.Zlib.DeflateStream(

                  output, Ionic.Zlib.CompressionMode.Compress,

                  Ionic.Zlib.CompressionLevel.BestSpeed))

                {

                    compressor.Write(str, 0, str.Length);

                }

                return output.ToArray();

            }

        }

        public static byte[] GZipByte(byte[] str)

        {

            if (str == null)

            {

                return null;

            }

            using (var output = new MemoryStream())

            {

                using (

                  var compressor = new Ionic.Zlib.GZipStream(

                  output, Ionic.Zlib.CompressionMode.Compress,

                  Ionic.Zlib.CompressionLevel.BestSpeed))

                {

                    compressor.Write(str, 0, str.Length);

                }

                

                return output.ToArray();

            }

        }

//请求的单元测试

[TestMethod]

        public void DeflateTest()

        {

            string html = string.Empty;

            string postUrl = "http://localhost:8087/api/Contacts/DeflateTest";

            string paramData = "userId=jlk456j5";

            Encoding dataEncode = Encoding.UTF8;

            try

            {

                byte[] byteArray = dataEncode.GetBytes(paramData); //转化

                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));

                webReq.Method = "POST";

                webReq.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

                webReq.ContentLength = byteArray.Length;

                //webReq.Headers["userId"] = DESHelper.Encrypt("1382888655");

                //webReq.Headers["userPwd"] = DESHelper.Encrypt("123456789");

                Stream newStream = webReq.GetRequestStream();

                newStream.Write(byteArray, 0, byteArray.Length);//写入参数

                newStream.Close();

                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();

                ////0

                ////StreamReader sr = new StreamReader(response.GetResponseStream());

                ////html = sr.ReadToEnd();

                ////sr.Close();

                //using (var s = response.GetResponseStream())

                //{

                //    Encoding encode = Encoding.GetEncoding("utf-8");

                //    Byte[] read = new Byte[512];

                //    int bytes = s.Read(read, 0, 512);

                //    while (bytes > 0)

                //    {

                //        html += encode.GetString(read, 0, bytes);

                //        bytes = s.Read(read, 0, 512);

                //    }

                //}

                //2

                Stream zipstream = response.GetResponseStream();

                byte[] zipByte = ToByteArray(zipstream);

                html = DeflateDecompress(zipByte);

                response.Close();

                newStream.Close();

            }

            catch (Exception ex)

            {

                string tt = "";

            }

            string twt = html;

            //html = DESHelper.DesDecrypt(html);

        }

        private byte[] ToByteArray(Stream stream)

        {

            byte[] buffer = new byte[32768];

            using (MemoryStream ms = new MemoryStream())

            {

                while (true)

                {

                    int read = stream.Read(buffer, 0, buffer.Length);

                    if (read <= 0)

                        return ms.ToArray();

                    ms.Write(buffer, 0, read);

                }

            }

        }

        private string DeflateDecompress(byte[] buffer)

        {

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())

            {

                ms.Write(buffer, 0, buffer.Length);

                ms.Position = 0;

                //using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))

                //{

                //    stream.Flush();

                //    int nSize = 16 * 1024 + 256;    //假设字符串不会超过16K

                //    byte[] decompr
4000
essBuffer = new byte[nSize];

                //    int nSizeIncept = stream.Read(decompressBuffer, 0, nSize);

                //    stream.Close();

                //    return System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept);   //转换为普通的字符串

                //}

                using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))

                {

                    stream.Flush();

                    byte[] decompressBuffer = ToByteArray(stream);

                    int nSizeIncept = decompressBuffer.Length;

                    stream.Close();

                    return System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept);   //转换为普通的字符串

                }

            }

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: