2016-12-09 75 views
0

我的应用程序从网上下载一个压缩的XML文件,并试图创建XML阅读:解压缩XML饲料

var fullReportUrl = "http://..."; // valid url here 
//client below is an instance of HttpClient 
var fullReportResponse = client.GetAsync(fullReportUrl).Result; 

var zippedXmlStream = fullReportResponse.Content.ReadAsStreamAsync().Result; 

XmlReader xmlReader = null; 
using(var gZipStream = new GZipStream(zippedXmlStream, CompressionMode.Decompress)) 
{ 
    try 
    { 
     xmlReader = XmlReader.Create(gZipStream, settings); 
    } 
    catch (Exception xmlEx) 
    { 

    } 
} 

当我尝试创建XML阅读器我得到一个错误:

“魔法在gzip头号码不正确。请确保您传递一个gzip流。

enter image description here

当我在浏览器中使用URL时,我成功下载了格式良好的XML文件的zip文件。我的操作系统能够解压缩它,没有任何问题。我检查了下载文件的前两个字符,它们看起来像'ZIP',这与ZIP格式一致。

我可能会错过流转换中的一步。我究竟做错了什么?

+0

您是否尝试过答案? –

回答

1

您不需要使用GzipStream来解压缩任何http响应HttpClient。您可以使用HttpClientHandlerAutomaticDecompression使HttpClient自动为您解压缩请求。

HttpClientHandler handler = new HttpClientHandler() 
{ 
    // both gzip and deflate 
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate 
}; 

using (var client = new HttpClient(handler)) 
{ 
    var fullReportResponse = client.GetAsync(fullReportUrl).Result; 
} 

编辑1:

的Web服务器不会gzip输出所有的请求。首先,他们检查accept-encoding标题,如果标题已设置并且类似Accept-Encoding: deflate, gzip;q=1.0, *;q=0.5 Web服务器了解客户端可支持gzipdeflate,则Web服务器可能(取决于应用程序逻辑或服务器配置)将输出压缩为gzipdeflate。在你的情况下,我不认为你已经设置了accept-encoding标题,所以Web响应将会返回未压缩。虽然我建议你尝试上面的代码。

Read more about accept-encoding on MDN

+0

嘿,谢谢你的回复,但是设置AutmaticDecompression不起作用。我仍然得到压缩的字节流。我在这里添加更多细节http://stackoverflow.com/questions/41353557/download-and-unzip-xml-file – AstroSharp