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协议访问服务
最新推荐文章于 2022-12-09 15:09:28 发布