WebApi series ~ Decompress the HttpClient response stream, webapihttpclient

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.