GZIP压缩

C# 端服务器进行压缩,安卓解压缩


class GZIP
    {

        /// 
        /// 将传入字符串以GZip算法压缩后,返回Base64编码字符
        /// 
        /// 需要压缩的字符串
        /// 压缩后的Base64编码的字符串
        public static string GZipCompressString(string rawString)
        {
            if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
            {
                return "";
            }
            else
            {
                byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString());
                byte[] zippedData = Compress(rawData);
                return (string)(Convert.ToBase64String(zippedData));
            }

        }


        /// 
        /// GZip压缩
        /// 
        /// 
        /// 
        private static byte[] Compress(byte[] rawData)
        {
            MemoryStream ms = new MemoryStream();
            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
            compressedzipStream.Write(rawData, 0, rawData.Length);
            compressedzipStream.Close();
            return ms.ToArray();
        }



        public static string UnZip(string value)
        {
            byte[] byteArray = Convert.FromBase64String(value);
            byte[] tmpArray;

            using (MemoryStream msOut = new MemoryStream())
            {
                using (MemoryStream msIn = new MemoryStream(byteArray))
                {
                    using (GZipStream swZip = new GZipStream(msIn, CompressionMode.Decompress))
                    {
                        swZip.CopyTo(msOut);
                        tmpArray = msOut.ToArray();
                    }
                }
            }
            return Encoding.UTF8.GetString(tmpArray);
        }
    }

安卓端解压缩

public static String uncompress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return "";
        }
        byte[] t= Base64.decode(str.getBytes(), Base64.DEFAULT);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(t);
        GZIPInputStream gunzip = null;
        try {
            gunzip = new GZIPInputStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            in.close();
            out.close();
            gunzip.close();
        }


        return out.toString("UTF-8");
    }



你可能感兴趣的:(安卓)