我有以下代码:
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/test.xml.gz");
request.UserAgent = "TEST";
request.Accept = "*/*";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
var response = (HttpWebResponse)request.GetResponse();
var stream = response.GetResponseStream();
var buffer = new byte[4096];
int read;
if (File.Exists("test.txt"))
File.Delete("test.txt");
var file = new FileStream("test.txt", FileMode.CreateNew);
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
file.Write(buffer, 0, read);
file.Close();
stream.Dispose();
当我在Windows上运行它时,我将文件解压缩为8m。当我在mono test.txt上运行它是压缩数据的521k。
我正在使用Tarball汇编的Mono 3.2.6。(编辑:在Debian 7.3上安装在/usr/local/lib下)
我在做错了什么,还是此功能当前不支持单声道?
i似乎支持自动压缩,但实现仅取决于服务器发送的标题。在我的特殊情况下,我试图抓取一个糟糕的网站,即使响应被压缩,该网站即使不会发送正确的内容编码。我的猜测是,MS在典型的MS时尚中尝试超越标题检查,也许会添加GZ Magic的前两个字节等。
无论如何,对于将来可能会在这个地方发现自己的任何人,这是我的解决方案:
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/test.xml.gz");
request.Accept = "*/*";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
var response = (HttpWebResponse)request.GetResponse();
var mem = new MemoryStream() as Stream;
using (var stream = response.GetResponseStream())
stream.CopyTo(mem);
var bytes = (mem as MemoryStream).GetBuffer();
if (bytes[0] == 'x1F' && bytes[1] == 'x8B')
{
mem.Position = 0;
mem = new GZipStream(mem, CompressionMode.Decompress);
var uncompressed = new MemoryStream(bytes.Length * 20);
mem.CopyTo(uncompressed);
mem.Dispose();
mem = uncompressed;
}
if (File.Exists("lala.txt"))
File.Delete("lala.txt");
var file = new FileStream("lala.txt", FileMode.CreateNew);
mem.Position = 0;
mem.CopyTo(file);
file.Close();
(注意:我在这里没有正确处理所有内容,这只是示例代码。)