字符串WebService上先zip压缩再base64编码后传输

来源:互联网 发布:数据魔方没有了吗 编辑:程序博客网 时间:2024/05/21 06:54

先对字符串进行zip压缩,再进行base64编码

public string ZipBase64(string xml)        {            //压缩            string compressStr = "";            byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(xml);            try            {                MemoryStream ms = new MemoryStream();                GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);                zip.Write(compressBeforeByte, 0, compressBeforeByte.Length);                zip.Close();                byte[] buffer = new byte[ms.Length];                ms.Position = 0;                ms.Read(buffer, 0, buffer.Length);                ms.Close();                compressStr= Convert.ToBase64String(buffer);            }            catch (Exception e)            {                throw new Exception(e.Message);            }            //base64编码            byte[] encData_byte = new byte[compressStr.Length];            encData_byte = System.Text.Encoding.UTF8.GetBytes(compressStr);            xml= Convert.ToBase64String(encData_byte);            return xml;        }


得到zip压缩再base64编码的字符串后对其进行base64解码再解压

public string UnzipBase64(string xml)        {            //base64解码            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();            System.Text.Decoder utf8Decode = encoder.GetDecoder();            byte[] todecode_byte = Convert.FromBase64String(xml);            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);            char[] decoded_char = new char[charCount];            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);            string decoded = new String(decoded_char);            //解压缩            byte[] compressBeforeByte = Convert.FromBase64String(decoded);            byte[] buffer = new byte[0x1000];            try            {                MemoryStream ms = new MemoryStream(compressBeforeByte);                GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);                MemoryStream msreader = new MemoryStream();                while (true)                {                    int reader = zip.Read(buffer, 0, buffer.Length);                    if (reader <= 0)                    {                        break;                    }                    msreader.Write(buffer, 0, reader);                }                zip.Close();                ms.Close();                msreader.Position = 0;                buffer = msreader.ToArray();                msreader.Close();            }            catch (Exception e)            {                throw new Exception(e.Message);            }            byte[] compressAfterByte = buffer;            xml = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);            return xml;        }


 

原创粉丝点击