利用C#改寫JAVA中的Base64.DecodeBase64以及Inflater解碼


最近正在進行項目服務的移植工作,即將JAVA服務的程序移植到DotNet平台中。

在JAVA程序中,有個HTTP請求數據頭中,包含一個BASE64編碼的字符串,例如:

eJyVjMENgDAMA1fpBMjnIkp3ZzZEpAa1PLmXY10sDdqBqr54Ww5AthG7zxJYa0MYr9p7bPFnK/uqjCj06y7JfHwAX3AhhA==

現在需要將這個字符串轉化成原始字符串,原始字符串包含許多重要的信息。

我們來看下JAVA是如何實現這個程序的:

String str = "……";
System.out.println(new String(ZipUtil.decompressByteArray(Base64.decodeBase64(str.getBytes()))));

其中Base64為commons-codec-1.3.jar包中的一個類。這個包主要包括核心的算法,比如MD5,SHA1等等,還有一些常規加密解密的算法。

而ZipUtil.decompressByteArray的方法實現為:

復制代碼
代碼
public static byte[] decompressByteArray(byte abyte0[]) 

    Inflater inflater = new Inflater(); 
    inflater.setInput(abyte0); 
    ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(abyte0.length); 
    byte abyte1[] = new byte[1024]; 
    while (!inflater.finished()) 
        try 
        { 
            int i = inflater.inflate(abyte1); 
            bytearrayoutputstream.write(abyte1, 0, i); 
        } 
        catch (DataFormatException dataformatexception) { } 
    try 
    { 
        bytearrayoutputstream.close(); 
    } 
    catch (IOException ioexception) { } 
    return bytearrayoutputstream.toByteArray(); 
}
復制代碼

得出的結果為:

image

這個得到具有一定協議的數據格式,這是項目制定的,這里不必多說。

現在我們來看下C#該如何實現它:

復制代碼
代碼
        [Test]
        public void Base64Test()
        {
            string baseStr = "eJyVjMENgDAMA1fpBMjnIkp3ZzZEpAa1PLmXY10sDdqBqr54Ww5AthG7zxJYa0MYr9p7bPFnK/uqjCj06y7JfHwAX3AhhA==";
            // Base64解碼
            byte[] baseBytes = Convert.FromBase64String(baseStr);
            // Inflater解壓
            string resultStr = Decompress(baseBytes);

            Console.WriteLine(resultStr);
        }

        /// <summary>
        /// Inflater解壓
        /// </summary>
        /// <param name="baseBytes"></param>
        /// <returns></returns>
        public string Decompress(byte[] baseBytes)
        {
            string resultStr = string.Empty;
            using (MemoryStream memoryStream = new MemoryStream(baseBytes))
            {
                using (InflaterInputStream inf = new InflaterInputStream(memoryStream))
                {
                    using (MemoryStream buffer = new MemoryStream())
                    {
                        byte[] result = new byte[1024];

                        int resLen;
                        while ((resLen = inf.Read(result, 0, result.Length)) > 0)
                        {
                            buffer.Write(result, 0, resLen);
                        }
                        resultStr = Encoding.Default.GetString(result);
                    }
                }
            }
            return resultStr;
        }
復制代碼

其中InflaterInputStream的類來自於ICSharpCode.SharpZipLib.dll中。

得出的結果為:

image

可以發現得到的結果是和JAVA版一樣的,程序得到實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM