2016-12-09 80 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