WebApi系列~对HttpClient的响应流进行解压

2018-06-22 06:16:55来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

回到目录

有时我们的请求头为ContentEncoding添加了gzip进行了压缩,而服务端返回数据时也会对它进行gzip压缩,如果在这种情况下,你直接头响应流会是乱码,而必须先进行压缩,大叔将这块的逻辑进行了抽取,它把抽取到了方法里,自动使用这个功能!

        /// <summary>
        /// 对流进行解压
        /// </summary>
        /// <param name="response"></param>
        static void UnGZip(HttpResponseMessage response)
        {
            bool isGzip = response.Content.Headers.ContentEncoding.Contains("gzip");
            if (isGzip)
            {
                Stream decompressedStream = new MemoryStream();
                using (var gzipStream = new GZipStream(response.Content.ReadAsStreamAsync().Result, CompressionMode.Decompress))
                {
                    gzipStream.CopyToAsync(decompressedStream);
                }
                decompressedStream.Seek(0, SeekOrigin.Begin);

                var originContent = response.Content;
                response.Content = new StreamContent(decompressedStream);
            }
        }

在GET,POST,PUT,DELETE方法的响应流时,进行装饰,把流进行解压即可!

        public static T Post<T>(string url, object argument = null, CookieContainer cookieContainer = null)
        {
            string sret = "";
            if (cookieContainer == null)
                cookieContainer = new CookieContainer();
            using (HttpClientHandler clientHandler = new HttpClientHandler() { CookieContainer = cookieContainer })
            using (HttpClient client = new HttpClient(clientHandler))
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                string sargument = Newtonsoft.Json.JsonConvert.SerializeObject(argument);
                StringContent argumentContent = new StringContent(sargument, Encoding.UTF8, "application/json");
                HttpResponseMessage response = client.PostAsync(url, argumentContent).Result;
                if (response.IsSuccessStatusCode)
                {
                    UnGZip(response);
                    sret = response.Content.ReadAsStringAsync().Result;
                }
                else
                {
                 throw new Exception(response.StatusCode.ToString());
                }
                if (!string.IsNullOrEmpty(sret))
                {

                    T ret = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(sret);
                    return ret;
                }
                else
                {
                    return default(T);
                }
            }
        }

这样你的响应流就被解开了!

挺方便!

回到目录

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:【译】Asp.Net Identity Cookies 格式化

下一篇:MVC初级知识之三——View与Controller的讲解(以近乎产品源码为