对于这篇长篇文章感到抱歉,我会尽量缩短篇幅。
我正在使用json API(当然没有文档),它会返回如下内容:
{
uncompressedlength: 743637,
compressedlength: 234532,
compresseddata: "lkhfdsbjhfgdsfgjhsgfjgsdkjhfgj"
}
压缩数据(在这种情况下为xml),然后压缩我尝试提取的base64编码数据。我所拥有的只是用perl编写的演示代码来解码它:
use Compress::Zlib qw(uncompress);
use MIME::Base64 qw(decode_base64);
my $uncompresseddata = uncompress(decode_base64($compresseddata));
看起来很简单。
我尝试了很多方法来解码base64:
private string DecodeFromBase64(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.Encoding.Unicode.GetString(encodedDataAsBytes);
return returnValue;
}
public string base64Decode(string data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(data);
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 result = new String(decoded_char);
return result;
}
catch (Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}
我尝试过使用Ionic.Zip.dll(DotNetZip?)和zlib.net来扩充Zlib压缩。但是一切都错了。我试图找出问题的来源。它是base64解码还是Inflate?
使用zlib进行充气时总是出错:使用zlib.net时出现错误的Magic Number错误,使用DotNetZip时出现“Bad state(存储块长度无效)”:
string decoded = DecodeFromBase64(compresseddata);
string decompressed = UnZipStr(GetBytes(decoded));
public static string UnZipStr(byte[] input)
{
using (MemoryStream inputStream = new MemoryStream(input))
{
using (Ionic.Zlib.DeflateStream zip =
new Ionic.Zlib.DeflateStream(inputStream, Ionic.Zlib.CompressionMode.Decompress))
{
using (StreamReader reader =
new StreamReader(zip, System.Text.Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
看完之后: http://george.chiramattel.com/blog/2007/09/deflatestream-block-length-does-not-match.html 并听取其中一条评论。我将代码更改为:
MemoryStream memStream = new MemoryStream(Convert.FromBase64String(compresseddata));
memStream.ReadByte();
memStream.ReadByte();
DeflateStream deflate = new DeflateStream(memStream, CompressionMode.Decompress);
string doc = new StreamReader(deflate, System.Text.Encoding.UTF8).ReadToEnd();
它工作正常。
答案 0 :(得分:3)
这是罪魁祸首:
http://george.chiramattel.com/blog/2007/09/deflatestream-block-length-does-not-match.html
通过跳过前两个字节,我可以将其简化为:
MemoryStream memStream = new MemoryStream(Convert.FromBase64String(compresseddata));
memStream.ReadByte();
memStream.ReadByte();
DeflateStream deflate = new DeflateStream(memStream, CompressionMode.Decompress);
string doc = new StreamReader(deflate, System.Text.Encoding.UTF8).ReadToEnd();
答案 1 :(得分:1)
首先,使用System.IO.Compression.DeflateStream
重新充气数据。您应该能够使用MemoryStream
作为输入流。您可以使用byte[]
的{{1}}结果创建一个MemoryStream。
您可能会在尝试将base64结果转换为给定编码时遇到各种麻烦;直接使用原始数据进行Deflate。