.NET:是否有可能得到的HttpWebRequest自动DECOM preSS gzip压缩的反应? [英] .NET: Is it possible to get HttpWebRequest to automatically decompress gzip'd responses?
问题描述
在<一个href="http://stackoverflow.com/questions/2813989/how-do-i-read-a-secure-rss-feed-into-a-syndicationfeed-without-providing-credenti/2815624#2815624">this回答,我描述了我是如何使出了HttpWebResponse wrappnig各地的响应流的GZipStream,以DECOM preSS它。
In this answer, I described how I resorted to wrappnig a GZipStream around the response stream in a HttpWebResponse, in order to decompress it.
相关code是这样的:
The relevant code looks like this:
HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create(url);
hwr.CookieContainer =
PersistentCookies.GetCookieContainerForUrl(url);
hwr.Accept = "text/xml, */*";
hwr.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us");
hwr.UserAgent = "My special app";
hwr.KeepAlive = true;
using (var resp = (HttpWebResponse) hwr.GetResponse())
{
using(Stream s = resp.GetResponseStream())
{
Stream s2 = s;
if (resp.ContentEncoding.ToLower().Contains("gzip"))
s2 = new GZipStream(s2, CompressionMode.Decompress);
else if (resp.ContentEncoding.ToLower().Contains("deflate"))
s2 = new DeflateStream(s2, CompressionMode.Decompress);
... use s2 ...
}
}
有没有办法让HttpWebResponse为解-COM pressing流,自动?换句话说,这是一种对我来说,以消除上述code以下内容:
Is there a way to get HttpWebResponse to provide a de-compressing stream, automatically? In other words, a way for me to eliminate the following from the above code:
Stream s2 = s;
if (resp.ContentEncoding.ToLower().Contains("gzip"))
s2 = new GZipStream(s2, CompressionMode.Decompress);
else if (resp.ContentEncoding.ToLower().Contains("deflate"))
s2 = new DeflateStream(s2, CompressionMode.Decompress);
感谢。
推荐答案
使用的<一个href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.automaticdecom$p$pssion.aspx">HttpWebRequest.AutomaticDecom$p$pssion属性如下:
HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create(url);
hwr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
这是没有必要手动添加接受编码
HTTP标头;当属性用于它会自动被添加。
It's not necessary to manually add the Accept-Encoding
HTTP header; it will automatically be added when that property is used.
(另外,我知道这只是例子code,但 HttpWebResponse
对象应放置在使用
块,它的正确处置,当你使用它已经完成了。)
(Also, I know this is just example code, but the HttpWebResponse
object should be placed in a using
block so it's disposed correctly when you've finished using it.)
这篇关于.NET:是否有可能得到的HttpWebRequest自动DECOM preSS gzip压缩的反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!