C# Http协议访问服务

来源:互联网 发布:数据库视频教程下载 编辑:程序博客网 时间:2024/05/22 02:03
        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 "";                }            }        }