using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.Core.Utilities { 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) { public static string HttpGet(string url, Dictionary? headers = null) { HttpClient client = new HttpClient(); 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; } try { byte[] resultBytes = client.GetByteArrayAsync(url).Result; return Encoding.UTF8.GetString(resultBytes); } catch { return string.Empty; } } public static string HttpPost(string url, string postData, Dictionary? headers = null, string contentType = "", int timeout = 0, Encoding? encoding = null) { HttpClient client = new HttpClient(); if (headers != null) { foreach (var header in headers) { client.DefaultRequestHeaders.Add(header.Key, header.Value); } HttpResponseMessage response = client.GetAsync(url).Result; return response.Content.ReadAsStringAsync().Result; } } HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8); if (!string.IsNullOrWhiteSpace(contentType)) { content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); } try { using HttpResponseMessage responseMessage = client.PostAsync(url, content).Result; byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result; return Encoding.UTF8.GetString(resultBytes); } catch { return string.Empty; } } } }