using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using System.Web; namespace EShang.Common { /// /// 通用的HTTP请求类 /// public class HttpUtil { #region 方法 -> HTTP报文请求【POST】 /// /// HTTP报文请求【POST】 /// /// 请求参数 /// 请求url /// 资源的媒体类型,默认application/x-www-form-urlencoded /// 超时时间(TCP连接建立的时间和整个请求完成的时间超出了设置的时间,就抛出异常,程序中断) /// 服务器通信的默认安全协议(众马对账通信需使用Tls12,WCF默认通道即可) /// public static string HttpUrlPost(string postDataStr, string RequestUrl, string ContentType = "application/x-www-form-urlencoded", int timeout = 0, SecurityProtocolType securityProtocol = SecurityProtocolType.SystemDefault) { try { CookieContainer cookieContainer = new CookieContainer(); byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postDataStr); // 设置提交的相关参数 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); HttpWebRequest request = WebRequest.Create(RequestUrl) as HttpWebRequest; if (timeout > 0) { request.Timeout = timeout * 1000; } request.Method = "POST"; request.KeepAlive = false; request.ContentType = ContentType; request.CookieContainer = cookieContainer; request.ContentLength = postBytes.Length; using (System.IO.Stream reqStream = request.GetRequestStream()) { reqStream.Write(postBytes, 0, postBytes.Length); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { //在这里对接收到的页面内容进行处理 //直到request.GetResponse()程序才开始向目标网页发送post请求 System.IO.Stream responseStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8")); string val = reader.ReadToEnd(); return val; } } catch (Exception ex) { SuperMap.RealEstate.Utility.ErrorLogHelper.Write(ex, "Post请求", "Post请求:" + postDataStr + "," + RequestUrl); return ex.ToString(); } } /// /// HTTP报文请求【POST】 /// /// 报文内容 /// 请求地址 /// 资源的媒体类型 /// 超时时间 /// 请求的接受类型 /// 请求头 /// public static string HttpUrlPost(string jsonData, string url, string contentType, int timeoutSeconds, string acceptType, Dictionary headers) { try { // 创建 HttpWebRequest HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; // 设置请求方法为 POST request.ContentType = contentType; // 设置请求体的 ContentType if (!string.IsNullOrWhiteSpace(acceptType)) { request.Accept = acceptType; // 设置请求的接受类型 } else { request.Accept = "*/*"; } if (string.IsNullOrWhiteSpace(HttpContext.Current.Request.UserAgent)) { request.UserAgent = "Windows Server2012R2;WebApi 4.0"; } else { request.UserAgent = HttpContext.Current.Request.UserAgent; } request.Timeout = timeoutSeconds * 1000; // 设置超时时间,单位为毫秒 // 添加请求头 if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } // 写入请求体 using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { writer.Write(jsonData); writer.Flush(); } // 获取响应 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { // 如果请求成功,读取返回内容 using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } catch (WebException ex) { // 处理错误(如超时、网络错误等) using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream())) { string errorResponse = reader.ReadToEnd(); return $"Error: {ex.Message}, Response: {errorResponse}"; } } catch (Exception ex) { // 处理其他类型的异常 return $"Exception: {ex.Message}"; } } public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } #endregion #region 方法 -> HTTP报文请求【GET】 /// /// HTTP报文请求【GET】 /// /// 请求url /// 资源的媒体类型,默认application/x-www-form-urlencoded /// 超时时间(TCP连接建立的时间和整个请求完成的时间超出了设置的时间,就抛出异常,程序中断) /// public static string HttpUrlGet(string RequestUrl, string ContentType = "application/x-www-form-urlencoded", int timeout = 0) { try { // 设置提交的相关参数 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); //根据url创建HttpWebRequest对象 HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(RequestUrl); objRequest.Method = "get"; objRequest.KeepAlive = false; objRequest.ContentType = ContentType; if (timeout > 0) { objRequest.Timeout = timeout * 1000; } //读取服务器返回信息 HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); //using作为语句,用于定义一个范围,在此范围的末尾将释放对象 using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) { //ReadToEnd适用于小文件的读取,一次性的返回整个文件 string Result = sr.ReadToEnd(); sr.Close(); return Result; } } catch (Exception ex) { SuperMap.RealEstate.Utility.ErrorLogHelper.Write(ex, "Get请求", "Get请求:" + RequestUrl); return ex.ToString(); } } #endregion #region 方法 -> 使用Post form-data方法上传数据、文件 /// /// 使用Post form-data方法上传数据、文件 /// /// /// Post表单内容 /// /// 默认20秒 /// Referer HTTP 标头 /// 响应内容的编码类型(默认utf-8) /// public static string PostForm(string url, List formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null, int timeOut = 20000) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); #region 初始化请求对象 request.Method = "POST"; request.Timeout = timeOut; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; request.KeepAlive = true; if (string.IsNullOrWhiteSpace(HttpContext.Current.Request.UserAgent)) { request.UserAgent = "Windows Server2012R2;WebApi 4.0"; } else { request.UserAgent = HttpContext.Current.Request.UserAgent; } if (!string.IsNullOrEmpty(refererUrl)) { request.Referer = refererUrl; } if (cookieContainer != null) { request.CookieContainer = cookieContainer; } #endregion string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符 request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); //请求流 var postStream = new MemoryStream(); #region 处理Form表单请求内容 //是否用Form上传文件 var formUploadFile = formItems != null && formItems.Count > 0; if (formUploadFile) { //文件数据模板 string fileFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + "\r\nContent-Type: application/octet-stream" + "\r\n\r\n"; //文本数据模板 string dataFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}"; foreach (var item in formItems) { string formdata = null; if (item.IsFile) { //上传文件 formdata = string.Format( fileFormdataTemplate, item.Key, //表单键 item.FileName); } else { //上传文本 formdata = string.Format( dataFormdataTemplate, item.Key, item.Value); } //统一处理 byte[] formdataBytes = null; //第一行不需要换行 if (postStream.Length == 0) formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2)); else formdataBytes = Encoding.UTF8.GetBytes(formdata); postStream.Write(formdataBytes, 0, formdataBytes.Length); //写入文件内容 if (item.FileContent != null && item.FileContent.Length > 0) { using (var stream = item.FileContent) { byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) { postStream.Write(buffer, 0, bytesRead); } } } } //结尾 var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); postStream.Write(footer, 0, footer.Length); } else { request.ContentType = "application/x-www-form-urlencoded"; } #endregion request.ContentLength = postStream.Length; #region 输入二进制流 if (postStream != null) { postStream.Position = 0; //直接写入流 Stream requestStream = request.GetRequestStream(); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } ////debug //postStream.Seek(0, SeekOrigin.Begin); //StreamReader sr = new StreamReader(postStream); //var postStr = sr.ReadToEnd(); postStream.Close();//关闭文件访问 } #endregion HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (cookieContainer != null) { response.Cookies = cookieContainer.GetCookies(response.ResponseUri); } using (Stream responseStream = response.GetResponseStream()) { using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8)) { string retString = myStreamReader.ReadToEnd(); return retString; } } } #endregion #region 方法 -> 请求移动业务的接口 /// /// 请求移动业务的接口 /// /// URL后面的参数 /// public static string PostMobileService(string parameters, string provinceCode) { string reString = ""; try { string _BaseUrl = ConfigurationManager.AppSettings[provinceCode]; string RequestUrl = _BaseUrl + parameters; reString = HttpUrlPost(parameters, RequestUrl); } catch (Exception ex) { reString = "error:" + ex.Message; } return reString; } #endregion } }