最近正在进行项目服务的移植工作,即将JAVA服务的程序移植到DotNet平台中。
在JAVA程序中,有个HTTP请求数据头中,包含一个BASE64编码的字符串,例如:
eJyVjMENgDAMA1fpBMjnIkp3ZzZEpAa1PLmXY10sDdqBqr54Ww5AthG7zxJYa0MYr9p7bPFnK/uqjCj06y7JfHwAX3AhhA==
现在需要将这个字符串转化成原始字符串,原始字符串包含许多重要的信息。
我们来看下JAVA是如何实现这个程序的:
String str="……";
System.out.println(newString(ZipUtil.decompressByteArray(Base64.decodeBase64(str.getBytes()))));
其中Base64为commons-codec-1.3.jar包中的一个类。这个包主要包括核心的算法,比如MD5,SHA1等等,还有一些常规加密解密的算法。
而ZipUtil.decompressByteArray的方法实现为:
代码
publicstaticbyte[] decompressByteArray(byteabyte0[])
{
Inflater inflater=newInflater();
inflater.setInput(abyte0);
ByteArrayOutputStream bytearrayoutputstream=newByteArrayOutputStream(abyte0.length);byteabyte1[]=newbyte[1024];while(!inflater.finished())try{inti=inflater.inflate(abyte1);
bytearrayoutputstream.write(abyte1,0, i);
}catch(DataFormatException dataformatexception) { }try{
bytearrayoutputstream.close();
}catch(IOException ioexception) { }returnbytearrayoutputstream.toByteArray();
}
得出的结果为:
这个得到具有一定协议的数据格式,这是项目制定的,这里不必多说。
现在我们来看下C#该如何实现它:
代码
[Test]publicvoidBase64Test()
{stringbaseStr="eJyVjMENgDAMA1fpBMjnIkp3ZzZEpAa1PLmXY10sDdqBqr54Ww5AthG7zxJYa0MYr9p7bPFnK/uqjCj06y7JfHwAX3AhhA==";//Base64解码byte[] baseBytes=Convert.FromBase64String(baseStr);//Inflater解压stringresultStr=Decompress(baseBytes);
Console.WriteLine(resultStr);
}//Inflater解压/publicstringDecompress(byte[] baseBytes)
{stringresultStr=string.Empty;using(MemoryStream memoryStream=newMemoryStream(baseBytes))
{using(InflaterInputStream inf=newInflaterInputStream(memoryStream))
{using(MemoryStream buffer=newMemoryStream())
{byte[] result=newbyte[1024];intresLen;while((resLen=inf.Read(result,0, result.Length))>0)
{
buffer.Write(result,0, resLen);
}
resultStr=Encoding.Default.GetString(result);
}
}
}returnresultStr;
}
其中InflaterInputStream的类来自于ICSharpCode.SharpZipLib.dll中。
得出的结果为:
可以发现得到的结果是和JAVA版一样的,程序得到实现。