想要解压从API获取的GZip压缩响应。尝试了下面的代码,但它总是返回以下结果:
\u001f�\b\0\0\0\0\0\0\0�Y]o........
我的代码是:
private string GetResponse(string sData, string sUrl)
{
try
{
string script = null;
try
{
string urlStr = @"" + sUrl + "?param=" + sData;
Uri url = new Uri(urlStr, UriKind.Absolute);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
script = reader.ReadToEnd();
}
}
catch (System.Net.Sockets.SocketException)
{
// The remote site is currently down. Try again next time.
}
catch (UriFormatException)
{
// Only valid absolute URLs are accepted
}
return script;
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
我从很多参考资料中找到了上面的自动解压代码。但是最终它对我没有用。为了解压缩的数据,我尝试了下面的函数:
private string DecompressGZIP(string compressedText)
{
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
using (var memoryStream = new MemoryStream())
{
int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);
var buffer = new byte[dataLength];
memoryStream.Position = 0;
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
gZipStream.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
但是,它在第一行代码本身就失败了,因为出现了以下异常:System.FormatException:“输入不是有效的Base-64字符串,因为它包含一个非Base64字符,超过两个填充字符或填充字符中有一个非法字符。”
由于我是初学者,希望您能指导我.....提前感谢....
request.AutomaticDecompression = DecompressionMethods.GZip
应该已经为您完成了。请阅读[ask]并重新开始,创建一个[mcve]。而且,在英语中,您不必将随机单词大写。 - CodeCaster