[Reprinted] About gzip compression enabled for HttpWebRequest and httpwebrequestgzip
Generally, gzip compression is not enabled when an HttpWebRequest object is used. If the data returned by the server is large, we need to enable gzip compression. How can we enable it?
1. Add the following Header to the HttpWebRequest object:
Request. Headers. Add ("Accept-Encoding", "gzip ");
2. decode the received stream:
private string GetResponseBody(HttpWebResponse response){ string responseBody = string.Empty; if (response.ContentEncoding.ToLower().Contains("gzip")) { using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)) { using (StreamReaderreader = new StreamReader(stream)) { responseBody = reader.ReadToEnd(); } } } else if (response.ContentEncoding.ToLower().Contains("deflate")) { using (DeflateStream stream = new DeflateStream( response.GetResponseStream(), CompressionMode.Decompress)) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { responseBody = reader.ReadToEnd(); } } } else { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { responseBody = reader.ReadToEnd(); } } } return responseBody;}