本文介绍了解压缩xml feed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序从Web下载了一个压缩的xml文件,并尝试创建XML阅读器:

My application downloads a zipped xml file from the web and tries to create XML reader:

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阅读器时,出现错误:

When I try to create XML reader I get an error:

GZip标头中的魔术数字为不正确。请确保您正在传递GZip流。

当我在浏览器中使用URL时,我成功下载了其中包含格式正确的XML的zip文件。我的操作系统能够毫无问题地将其解压缩。我检查了其中的前两个字符

When I use the URL in the browser I succesfully download a zip file with a well formatted XML in it. My OS is able to unzip it without any issues. I examined the first two characters of the downloaded file and they appear to be 'PK' which is consistent with a ZIP format.

我可能会丢失流转换的步骤。我在做什么错? / p>

I might be missing a step in stream transformations. What am I doing wrong?

推荐答案

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

You don't need to use GzipStream for decompressing any http response with HttpClient. You can use HttpClientHandler AutomaticDecompression to make HttpClient decompress the request automatically for you.

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服务器认为客户端可以支持 gzip deflate ,因此Web服务器可能(取决于应用程序逻辑或服务器配置)将输出压缩为 gzip deflate 。在您的情况下,我认为您没有设置 accept-encoding 标头,因此网络响应将返回未压缩状态。尽管我建议您尝试上面的代码。

Web Servers won't gzip output all the requests. First they check accept-encoding header, if the header is set and it is something like Accept-Encoding: deflate, gzip;q=1.0, *;q=0.5 the web server understands the client could support gzip or deflate so Web Server might ( depends on the app logic or server configuration ) compress the output into gzip or deflate. In your scenario I don't think you have set accept-encoding header so the web response will return uncompressed. Although I recommend you to try the code above.

这篇关于解压缩xml feed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 02:06