WebApi系列~對HttpClient的(de)響(xiang)應流進行解壓
有時我們的(de)請求頭(tou)(tou)為ContentEncoding添加了gzip進(jin)行(xing)了壓(ya)縮,而服(fu)務端返回數據時也會(hui)對它進(jin)行(xing)gzip壓(ya)縮,如果在這(zhe)種情況下,你直(zhi)接頭(tou)(tou)響應流(liu)會(hui)是(shi)亂碼,而必(bi)須先進(jin)行(xing)壓(ya)縮,大叔將這(zhe)塊的(de)邏輯進(jin)行(xing)了抽取,它把抽取到了方法里,自動使用(yong)這(zhe)個(ge)功能!
/// <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方法的響(xiang)應流(liu)時,進行裝飾,把流(liu)進行解壓(ya)即(ji)可!
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); } } }
這樣你的響應流(liu)就(jiu)被解(jie)開(kai)了!
挺方便!