WebApi系列~对HttpClient的响应流进行解压
2017-11-02 15:11
281 查看
回到目录
有时我们的请求头为ContentEncoding添加了gzip进行了压缩,而服务端返回数据时也会对它进行gzip压缩,如果在这种情况下,你直接头响应流会是乱码,而必须先进行压缩,大叔将这块的逻辑进行了抽取,它把抽取到了方法里,自动使用这个功能!
在GET,POST,PUT,DELETE方法的响应流时,进行装饰,把流进行解压即可!
这样你的响应流就被解开了!
挺方便!
回到目录
有时我们的请求头为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的性能隐患(转)
- HttpCLient实现对被GZip压缩过的Response进行解压
- WebApi系列~HttpClient的性能隐患
- WebApi系列~HttpClient的性能隐患 - 转
- Http下的各种操作类.WebApi系列~通过HttpClient来调用Web Api接口
- ABP入门系列(16)——通过webapi与系统进行交互
- HttpCLient实现对被GZip压缩过的Response进行解压
- 使用httpclient对zip格式的响应数据解压
- WebApi系列~通过HttpClient来调用Web Api接口
- HttpCLient实现对被GZip压缩过的Response进行解压
- WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递
- WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递
- WebApi系列~实际项目中如何使用HttpClient向web api发异步Get和Post请求并且参数于具体实体类型
- WebApi系列~实际项目中如何使用HttpClient向web api发异步Get和Post请求并且参数于具体实体类型
- WebApi系列~通过HttpClient来调用Web Api接口