using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Text; using System.Threading.Tasks; namespace ICSSoft.Common { public class HTTPHelper { private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public static string HttpPost(string apiName, string url, string body) { try { //log.Debug(url + Environment.NewLine + body); Encoding encoding = Encoding.UTF8; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "POST"; request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*"; request.ContentType = "application/json; charset=utf-8"; // request.ContentType = "text/html, application/xhtml+xml"; byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding)) { return reader.ReadToEnd(); } } catch (System.Net.WebException ex) { log.Error(ex.ToString() + Environment.NewLine + url + Environment.NewLine + body); throw new Exception(apiName + "调用失败," + ex.Message); } } public static string HttpPost(string url, string body) { try { Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentLength = 110; request.ContentType = "application/json"; byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); log.Error(url + body); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) { return reader.ReadToEnd(); } } catch (WebException ex) { var res = (HttpWebResponse)ex.Response; StringBuilder sb = new StringBuilder(); StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8); sb.Append(sr.ReadToEnd()); //string ssb = sb.ToString(); //throw new Exception(sb.ToString()); return ""; } } /// /// 通过web api获取数据的方法 /// /// api的url /// 请求类型,默认是get /// post请求所携带的数据 /// public static string RequestData(string url, string method, string postData) { try { log.Error(postData); method = method.ToUpper(); //设置安全通信协议 我方公司服务器有些强制使用tls1.2的安全通信协议,所以至少包含SecurityProtocolType.Tls12 如果沒有SecurityProtocolType.Tls12设置会报错:HttpWebRequest底层连接已关闭:传送时发生意外错误 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; //创建请求实例 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //设置请求类型 request.Method = method; //设置请求消息主体的编码方法 request.ContentType = "application/json"; //POST方式處理 if (method == "POST") { //用UTF8字符集对post请求携带的数据进行编码,可防止中文乱码 byte[] byteArray = Encoding.UTF8.GetBytes(postData); //指定客户端post请求携带的数据的长度 request.ContentLength = byteArray.Length; //创建一个tream,用于写入post请求所携带的数据(该数据写入了请求体) Stream stream = request.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); } //获取请求的响应实例 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //获取读取流实体,用来以UTF8字符集读取响应流中的数据 StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //进行数据读取 string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); return retString; } catch (Exception ex) { //拋出異常 throw ex; } } public static string WorkDayPostData(string URL, string JsonData, string ContentType) { string str = string.Empty; try { WebRequest request = WebRequest.Create(URL); request.Method = "POST"; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(JsonData); request.ContentType = ContentType; request.ContentLength = bytes.Length; using (Stream postStream = request.GetRequestStream()) { postStream.Write(bytes, 0, bytes.Length); } request.Credentials = CredentialCache.DefaultCredentials; WebResponse response = null; try { response = request.GetResponse(); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) response = (WebResponse)ex.Response; } if (response != null) { using (StreamReader st = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8)) { str = System.Web.HttpUtility.UrlDecode(st.ReadToEnd()); } } } catch (Exception ex) { str = ex.Message; } return str; } public static void CreateObject(string URL, string DATA) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = DATA.Length; StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII); requestWriter.Write(DATA); requestWriter.Close(); try { WebResponse webResponse = request.GetResponse(); Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); Console.Out.WriteLine(response); responseReader.Close(); } catch (Exception e) { Console.Out.WriteLine("-----------------"); Console.Out.WriteLine(e.Message); } } public static string Post(string posturl, string jsonstr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(posturl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; //json字符串转为字节数组 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jsonstr); //设置请求的ContentLength request.ContentLength = bytes.Length; //发送请求,获得请求流 Stream stream; try { //获取用于写入请求数据的Stream对象 stream = request.GetRequestStream(); } catch (Exception ex) { stream = null; Console.WriteLine(ex.Message); } //把数据写入流 stream.Write(bytes, 0, bytes.Length); stream.Close(); HttpWebResponse response; try { //获得响应流 response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = ex.Response as HttpWebResponse; } Stream s = response.GetResponseStream(); StreamReader sr = new StreamReader(s, Encoding.UTF8); string strVal = sr.ReadToEnd().Trim(); sr.Close(); s.Close(); return strVal; } /// /// HTTP访问method 常用的几样 /// public enum HttpVerb { /// /// get:获取 /// GET, /// /// post:修改 /// POST, /// /// put:写入 /// PUT, /// /// delete:删除 /// DELETE } /// /// HTTP访问格式类型,根据Postman整理 /// public enum HttpContentType { /// /// text/plain /// Text, /// /// application/json /// JSON, /// /// application/xml /// XML, /// /// text/xml /// TextXML, /// /// text/html /// HTML, /// /// application/javascript /// Javascript } /// /// Rest方式访问方法,ContentType为application/json /// public class RestHelper { /// /// 请求的url地址 /// public string EndPoint { get; set; } /// /// 请求的方法,默认 GET /// public HttpVerb Method { get; set; } /// /// 格式类型:默认application/json /// public HttpContentType ContentType { get; set; } /// /// 传送的数据,如json字符串 /// public string PostData { get; set; } /// /// 编码规范,默认 UTF8 /// public Encoding HttpEncoding { get; set; } /// /// 构造函数 /// public RestHelper(HttpContentType contentType = HttpContentType.JSON) { EndPoint = ""; Method = HttpVerb.GET; ContentType = contentType; PostData = ""; HttpEncoding = Encoding.UTF8; } /// /// 构造函数 /// public RestHelper(string endpoint, HttpContentType contentType = HttpContentType.JSON) { EndPoint = endpoint; Method = HttpVerb.GET; ContentType = contentType; PostData = ""; HttpEncoding = Encoding.UTF8; } /// /// 构造函数 /// public RestHelper(string endpoint, HttpVerb method, HttpContentType contentType = HttpContentType.JSON) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = ""; HttpEncoding = Encoding.UTF8; } /// /// 构造函数 /// public RestHelper(string endpoint, HttpVerb method, string postData, HttpContentType contentType = HttpContentType.JSON) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = postData; HttpEncoding = Encoding.UTF8; } /// /// 构造函数 /// public RestHelper(string endpoint, Encoding encoding, HttpVerb method = HttpVerb.GET, string postData = "", HttpContentType contentType = HttpContentType.JSON) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = postData; HttpEncoding = encoding; } /// /// 直接访问 /// /// public string MakeRequest() { return MakeRequest(""); } /// /// 带参数访问,如 MakeRequest("?param=0") /// /// /// public string MakeRequest(string parameters) { try { var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters); request.Method = Method.ToString(); request.ContentLength = 0; request.ContentType = GetContentType(ContentType); //如果传送的数据不为空,并且方法是post或put if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT)) { var bytes = HttpEncoding.GetBytes(PostData);//编码方式,默认UTF-8 request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } using (var response = (HttpWebResponse)request.GetResponse()) { var responseValue = string.Empty; if (response.StatusCode != HttpStatusCode.OK) { var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode); throw new ApplicationException(message); } // grab the response using (var responseStream = response.GetResponseStream()) { if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { responseValue = reader.ReadToEnd(); } } } return responseValue; } } catch (Exception e) { throw new Exception(e.Message); } } /// /// 将content type转成字符串描述 /// /// /// private string GetContentType(HttpContentType contentType) { switch (contentType) { case HttpContentType.Text: return "text/plain"; case HttpContentType.JSON: return "application/json"; case HttpContentType.XML: return "application/xml"; case HttpContentType.TextXML: return "text/xml"; case HttpContentType.HTML: return "text/html"; case HttpContentType.Javascript: return "application/javascript"; default: return ""; } } } } }