WebApi系列~对HttpClient的响应流进行解压
有时我们的请求头为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); } } }
这样你的响应流就被解开了!
挺方便!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2016-11-02 爱上MVC~一个Action多套View模版的设计
2012-11-02 EF架构~看看下面这代码,你还敢用它的延时加载吗?