public static string HttpClientService(string url, Dictionary<string, string> parameters = null)
{
//设置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//创建HttpClient(注意传入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
if (parameters == null) parameters = new Dictionary<string, string>() { };
var content = new FormUrlEncodedContent(parameters);
//await异步等待回应
var response = http.PostAsync(url, content).Result;
//确保HTTP成功状态值
//response.EnsureSuccessStatusCode();
//此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Content.ReadAsStringAsync().Result;
}
else
{
return "";
}
}
}C# Http协议访问服务
最新推荐文章于 2025-05-13 03:04:23 发布
本文介绍了一种使用C#中的HttpClient进行POST请求的方法,并自动处理GZIP压缩响应的示例代码。通过设置HttpClientHandler的AutomaticDecompression属性来实现自动解压功能。
446

被折叠的 条评论
为什么被折叠?



