using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json; namespace Utility.Tools { public class HttpHelper { private static HttpWebRequest GetHttpWebRequest(string url, Dictionary headerDic, string method) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = method; if (headerDic != null && headerDic.Count > 0) { foreach (var h in headerDic) { request.Headers.Add(h.Key, h.Value); } } return request; } private static string GetUrlParamString(Dictionary paramDic) { StringBuilder sb = new StringBuilder(); if (paramDic == null || paramDic.Count() < 1) { return string.Empty; } foreach (var d in paramDic) { if (sb.Length < 1) { sb.AppendFormat("{0}={1}", d.Key, d.Value); } else { sb.AppendFormat("&{0}={1}", d.Key, d.Value); } } sb.Insert(0, "?"); return sb.ToString(); } private static string GetResponseString(HttpWebRequest request) { try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } } catch (WebException ex) { throw ex; } } public static string DoGet(string url, Dictionary paramDic = null, Dictionary headerDic = null) { var paramString = GetUrlParamString(paramDic); var request = GetHttpWebRequest(url + paramString, headerDic, "GET"); request.ContentType = "application/json"; try { return GetResponseString(request); } catch (WebException ex) { throw ex; } } public static string DoPost(string url, string jsonData, string logStr,string str, Dictionary headerDic = null) { var request = GetHttpWebRequest(url, headerDic, "POST"); request.ContentType = "application/json"; request.ContentLength = 0; //log路径 var logStr2 = $@".\log\{str}\{logStr}" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; if (!string.IsNullOrWhiteSpace(jsonData)) { byte[] buffer = Encoding.UTF8.GetBytes(jsonData); request.ContentLength = buffer.Length; try { request.GetRequestStream().Write(buffer, 0, buffer.Length); //记录log LogFile.SaveLogToFile($"{logStr}+{url}:( {jsonData} ),", logStr2); } catch (WebException ex) { LogFile.SaveLogToFile($"{logStr}+{url}:( {ex.Message} ),", logStr2); throw ex; } } try { var requestData = GetResponseString(request); LogFile.SaveLogToFile($"{logStr}+{url}反馈:( {requestData} ),", logStr2); return requestData; } catch (WebException ex) { LogFile.SaveLogToFile($"{logStr}+{url}反馈:( {ex.Message} ),", logStr2); throw ex; } } public static string DoPost(string url, Dictionary paramDic, string logStr,string str, Dictionary headerDic = null) { string jsonStr = null; if (paramDic != null && paramDic.Count() > 0) { jsonStr = JsonConvert.SerializeObject(paramDic); } return DoPost(url, jsonStr, logStr,str,headerDic); } } }