1. 程式人生 > >HttpWebRequest開啟gzip壓縮

HttpWebRequest開啟gzip壓縮

在用HttpWebRequest物件時,一般我們都沒有開啟gzip壓縮,如果服務端返回的資料比較大,這是我們需要開啟gzip壓縮,怎麼開啟了?

1.給HttpWebRequest物件,新增如下Header

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

        2.對接收到的流進行解碼

                  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;

       }