有時我們的請求頭為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); } } }
這樣你的響應流就被解開了!
挺方便!