有时我们的请求头为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); } } }
这样你的响应流就被解开了!
挺方便!
本文转自博客园张占岭(仓储大叔)的博客,原文链接:WebApi系列~对HttpClient的响应流进行解压,如需转载请自行联系原博主。
时间: 2024-10-14 17:27:04