WebApi series ~ Decompress the HttpClient response stream, webapihttpclient
Back to directory
Sometimes our request header is compressed by adding gzip to ContentEncoding, and the server will also perform gzip compression on the returned data. In this case, the response stream of your direct connection will be garbled, but compression must be performed first. Uncle extracts the logic of this piece, and it extracts it into the method to automatically use this function!
/// <Summary> /// extract the stream /// </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 );}}
In the response stream of the GET, POST, PUT, and DELETE methods, describe the stream and decompress the stream!
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); } } }
In this way, your response stream will be unlocked!
Very convenient!
Back to directory