您的位置:首页 > 理论基础 > 计算机网络

WebApi系列~对HttpClient的响应流进行解压

2017-11-02 15:11 281 查看
回到目录

有时我们的请求头为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);
}
}
}


这样你的响应流就被解开了!

挺方便!

回到目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: