using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Infrastructure { public class HttpHelper { /// /// 发起POST同步请求 /// /// /// /// /// application/xml、application/json、application/text、application/x-www-form-urlencoded /// 填充消息头 /// public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary headers = null) { postData = postData ?? ""; using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8)) { if (contentType != null) httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result; return response.Content.ReadAsStringAsync().Result; } } } /// /// 发起POST异步请求 /// /// /// /// application/xml、application/json、application/text、application/x-www-form-urlencoded /// 填充消息头 /// public static async Task HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary headers = null) { postData = postData ?? ""; using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8)) { if (contentType != null) httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = await client.PostAsync(url, httpContent); return await response.Content.ReadAsStringAsync(); } } } /// /// 发起GET同步请求 /// /// /// /// /// public static string HttpGet(string url, Dictionary headers = null) { using (HttpClient client = new HttpClient()) { if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } else { client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded"); client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); } try { HttpResponseMessage response = client.GetAsync(url).Result; return response.Content.ReadAsStringAsync().Result; } catch (Exception ex) { //TODO 打印日志 Console.WriteLine($"[Http请求出错]{url}|{ex.Message}"); } return ""; } } /// /// 发起GET异步请求 /// /// /// /// public static async Task HttpGetAsync(string url, Dictionary headers = null) { using (HttpClient client = new HttpClient()) { if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } HttpResponseMessage response = await client.GetAsync(url); return await response.Content.ReadAsStringAsync(); } } } }