zoukankan      html  css  js  c++  java
  • 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;

           }

  • 相关阅读:
    试题 E: 迷宫
    对拍程序
    人群中钻出个光头
    HDU-魔咒词典(字符串hash)
    第八集 你明明自己也生病了,却还是要陪着我
    智力问答 50倒计时
    数据结构
    LeetCode刷题 fIRST MISSING POSITIVE
    LeetCode Best to buy and sell stock
    LeetCode Rotatelmage
  • 原文地址:https://www.cnblogs.com/majiang/p/2759459.html
Copyright © 2011-2022 走看看