C# HttpWebRequest - Using Gzip Compression

…衆ロ難τιáo~ 提交于 2019-12-24 01:04:53

问题


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. I know what gzip is, and how it works, but I don't know how it works in C#.

Let's say I have a simple GET request:

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? How can I show the compressed size, and then the un-compressed size?

Thanks


回答1:


Make sure you state in your request that you can accept gzip'd responses. 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:


See this page for a synopsis of how GZip works with web requests in general.

The specific header you're going to need to send is Accept-Encoding: gzip. Normally, you'd need to add this to the request yourself (via the Headers collection), but there's a shortcut. 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.



来源:https://stackoverflow.com/questions/19006997/c-sharp-httpwebrequest-using-gzip-compression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!