简体   繁体   English

C#HttpWebRequest - 使用Gzip压缩

[英]C# HttpWebRequest - Using Gzip Compression

I have a program which makes lots of HttpWebRequests, and I read about using gzip compression to speed up the downloading of the response data. 我有一个程序,它产生了很多HttpWebRequests,我读到了使用gzip压缩来加速响应数据的下载。 I know what gzip is, and how it works, but I don't know how it works in C#. 我知道gzip是什么,以及它是如何工作的,但我不知道它在C#中是如何工作的。

Let's say I have a simple GET request: 假设我有一个简单的GET请求:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.com");
request.Method = "GET";
WebResponse response = request.GetResponse();

How could I make the response data be compressed in gzip? 如何在gzip中压缩响应数据? How can I show the compressed size, and then the un-compressed size? 如何显示压缩大小,然后显示未压缩的大小?

Thanks 谢谢

See this page for a synopsis of how GZip works with web requests in general. 有关GZip如何处理Web请求的概要,请参阅此页面

The specific header you're going to need to send is Accept-Encoding: gzip . 您需要发送的特定标头是Accept-Encoding: gzip Normally, you'd need to add this to the request yourself (via the Headers collection), but there's a shortcut. 通常,您需要自己(通过Headers集合)将此添加到请求中,但是有一个快捷方式。 Per this answer , all you need to do is add 根据这个答案 ,您需要做的就是添加

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

to your code. 你的代码。

Note that you probably won't be able to get the compressed/uncompressed sizes doing this - the request will automatically decompress it as it comes in. However, since you can't know ahead of time whether the server will even try to send you GZipped pages, it's not a useful thing to be testing. 请注意,您可能无法获得压缩/未压缩的大小 - 请求将在它进入时自动解压缩。但是,因为您无法提前知道服务器是否会尝试发送给您GZipped页面,测试它并不是一件有用的事情。

Make sure you state in your request that you can accept gzip'd responses. 请确保在您的请求中声明您可以接受gzip的回复。 So, after your code to create the request, do this: 因此,在创建请求的代码之后,执行以下操作:

request.Headers.Add("Accept-Encoding", "gzip");

This will tell the server to return it zipped, if it can. 如果可以,这将告诉服务器将其拉回拉链。

The only way I can think to show the size difference would be t make 2 calls, one with compression and one not, and compare the length of the returned response streams. 我能想到显示大小差异的唯一方法是进行2次调用,一次使用压缩,一次不进行,并比较返回的响应流的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM