using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace learun.util { /// /// 版 本 EasyCode EC管理后台 /// Copyright (c) 2019-present EC管理有限公司 /// 创建人:tobin /// 日 期:2019.09.11 /// 描 述:http方法 /// public class HttpMethods { /// /// 创建HttpClient /// /// public static HttpClient CreateHttpClient(string url, IDictionary cookies = null) { HttpClient httpclient; HttpClientHandler handler = new HttpClientHandler(); var uri = new Uri(url); if (cookies != null) { foreach (var key in cookies.Keys) { string one = key + "=" + cookies[key]; handler.CookieContainer.SetCookies(uri, one); } } //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; httpclient = new HttpClient(handler); } else { httpclient = new HttpClient(handler); } return httpclient; } /// /// post 请求 /// /// 请求地址 /// 请求参数 /// public static Task Post(string url, string jsonData) { HttpClient httpClient = CreateHttpClient(url); var postData = new StringContent(jsonData); postData.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); Task result = httpClient.PostAsync(url, postData).Result.Content.ReadAsStringAsync(); return result; } /// /// post 请求 /// /// 请求地址 /// public static Task Post(string url) { HttpClient httpClient = CreateHttpClient(url); var postData = new StringContent(""); postData.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); Task result = httpClient.PostAsync(url, postData).Result.Content.ReadAsStringAsync(); return result; } /// /// post 请求 /// /// 请求地址 /// 请求参数 /// public static Task Post(string url, byte[] req) { HttpClient httpClient = CreateHttpClient(url); var postData = new ByteArrayContent(req); Task result = httpClient.PostAsync(url, postData).Result.Content.ReadAsStringAsync(); return result; } /// /// get 请求 /// /// 请求地址 /// public static Task Get(string url) { HttpClient httpClient = CreateHttpClient(url); Task result = httpClient.GetAsync(url).Result.Content.ReadAsStringAsync(); return result; } } }