net 后台调用http 请求公共方法



public class HttpHelper { /// <summary> /// post请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="body">参数</param> /// <param name="headers">请求头部信息</param> /// <param name="callback">回调函数</param> /// <param name="decompress"></param> /// <returns></returns> public static async Task<string> Post(string url, object bodyObj, Dictionary<string, string> headers = null, DecompressionMethods decompress = DecompressionMethods.GZip) { var header = GetObj(headers); var body = JsonConvert.SerializeObject(bodyObj); HttpRequestMessage reqestObj = new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(body, Encoding.UTF8, header.ContentType) }; SetHead(reqestObj.Headers, headers); var handler = new HttpClientHandler() { UseCookies = false, AutomaticDecompression = decompress }; HttpClient client = new HttpClient(handler); //// 请求头填充数据 EditDefaultRequestHeaders(client, header); var res = await client.SendAsync(reqestObj); var responseBody = await res.Content.ReadAsStringAsync(); return responseBody; } /// <summary> /// post请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="body">参数</param> /// <param name="headers">请求头部信息</param> /// <param name="callback">回调函数</param> /// <param name="decompress"></param> /// <returns></returns> public static async Task<T> Post<T>(string url, object bodyObj, Dictionary<string, string> headers = null, DecompressionMethods decompress = DecompressionMethods.GZip) { var header = GetObj(headers); var body = JsonConvert.SerializeObject(bodyObj); HttpRequestMessage reqestObj = new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(body, Encoding.UTF8, header.ContentType) }; SetHead(reqestObj.Headers, headers); var handler = new HttpClientHandler() { UseCookies = false, AutomaticDecompression = decompress }; HttpClient client = new HttpClient(handler); //// 请求头填充数据 EditDefaultRequestHeaders(client, header); var res = await client.SendAsync(reqestObj); var responseBody = await res.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(responseBody); ; } /// <summary> /// get请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="headers">请求头部信息</param> /// <param name="decompress"></param> /// <returns></returns> public static async Task<string> Get(string url, Dictionary<string, string> headers = null, DecompressionMethods decompress = DecompressionMethods.GZip) { try { var header = GetObj(headers); var handler = new HttpClientHandler() { UseCookies = false, AutomaticDecompression = decompress }; HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, url); SetHead(req.Headers, headers); HttpClient client = new HttpClient(handler); client.DefaultRequestHeaders.Add("User-Agent", header.UserAgent); var res = await client.SendAsync(req); var str = await res.Content.ReadAsStringAsync(); return str; } catch (Exception ex) { return ex.Message; } } #region 私有方法 /// <summary> /// 如果存在要修改常用的请求头信息 /// </summary> /// <param name="client">请求对象</param> /// <param name="headerObj"></param> private static void EditDefaultRequestHeaders(HttpClient client, HeaderObj headerObj) { if (headerObj.UserAgent.IsNotEmpty()) { client.DefaultRequestHeaders.Add("User-Agent", headerObj.UserAgent); } if (headerObj.Referer.IsNotEmpty()) { client.DefaultRequestHeaders.Add("Referer", headerObj.Referer); } if (headerObj.Origin.IsNotEmpty()) { client.DefaultRequestHeaders.Add("Origin", headerObj.Origin); } if (headerObj.AcceptLanguage.IsNotEmpty()) { client.DefaultRequestHeaders.Add("AcceptLanguage", headerObj.AcceptLanguage); } if (headerObj.Connection.IsNotEmpty()) { client.DefaultRequestHeaders.Add("Connection", headerObj.Connection); } if (headerObj.Accept.IsNotEmpty()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(headerObj.Accept)); } } /// <summary> /// 请求头添加自定义参数 /// </summary> /// <param name="headers">请求头</param> /// <param name="dics">请求头参数</param> private static void SetHead(HttpRequestHeaders headers, Dictionary<string, string> dics) { if (dics != null) { foreach (KeyValuePair<string, string> item in dics) { if (item.Key == "Content-Type") continue; if (item.Key == "Referer") continue; if (item.Key == "Content-Length") continue; if (item.Key == "Accept") continue; if (item.Key == "Connection") continue; if (item.Key == "Host") continue; headers.Add(item.Key, item.Value); } } } public static Dictionary<string, string> GetHeader(string Header) { var dics = new Dictionary<string, string>(); var headerStr = Header; var lines = headerStr.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines) { if (string.IsNullOrWhiteSpace(line)) continue; var index = line.IndexOf(":"); if (index < 0) continue; var key = line.Substring(0, index); var val = line.Substring(index + 1, line.Length - index - 1); dics[key] = val.Trim().TrimEnd(';'); } return dics; } /// <summary> /// 赋值请求头对象 /// </summary> /// <param name="headers"></param> /// <returns></returns> private static HeaderObj GetObj(Dictionary<string, string> headers) { HeaderObj obj = new HeaderObj(); if (headers != null) { if (headers.ContainsKey("Content-Type")) { obj.ContentType = headers["Content-Type"]; } if (headers.ContainsKey("Referer")) { obj.Referer = headers["Referer"]; } if (headers.ContainsKey("Connection")) { obj.Connection = headers["Connection"]; } if (headers.ContainsKey("Accept")) { obj.Accept = headers["Accept"]; } if (headers.ContainsKey("User-Agent")) { obj.UserAgent = headers["User-Agent"]; } if (headers.ContainsKey("Origin")) { obj.Origin = headers["Origin"]; } if (headers.ContainsKey("Accept-Language")) { obj.AcceptLanguage = headers["Accept-Language"]; } } return obj; } #endregion } class HeaderObj { public string ContentType { get; set; } = "application/json"; public string UserAgent { get; set; } public string Referer { get; set; } public string Connection { get; set; } public string Origin { get; set; } public string AcceptLanguage { get; set; } public string Accept { get; set; } }

 

上一篇:8种品牌PLC单片机实现Modbus RTU串口通信协议主站视频教程


下一篇:Postgresql源码(31)Btree索引相关系统表和整体结构