using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Security; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace BayonetTransfer.Common { internal class HttpHelper { #region 方法 -> HttpGet /// /// Post请求方法 /// /// /// /// /// /// public static string HttpGet(string postData, string requestURL, string contentType = "application/x-www-form-urlencoded", int timeOut = 0) { try { CookieContainer cookieContainer = new CookieContainer(); byte[] postBytes = Encoding.UTF8.GetBytes(postData); // 设置提交的相关参数 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL); if (timeOut == 0) { timeOut = 5; } request.Timeout = timeOut * 1000; request.Method = "Get"; request.KeepAlive = false; request.ContentType = contentType; request.CookieContainer = cookieContainer; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //在这里对接收到的页面内容进行处理 Stream responseStream = response.GetResponseStream(); using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8)) { return reader.ReadToEnd(); } } } catch (WebException wex) { return wex.ToString(); } catch (Exception ex) { return ex.Message; } } #endregion #region 方法 -> HttpPost /// /// Post请求方法 /// /// /// /// /// /// public static string HttpPost(string postData, string requestURL, string contentType = "application/x-www-form-urlencoded", int timeOut = 0) { CookieContainer cookieContainer = new CookieContainer(); byte[] postBytes = Encoding.UTF8.GetBytes(postData); // 设置提交的相关参数 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL); if (timeOut == 0) { timeOut = 5; } request.Timeout = timeOut * 1000; request.Method = "POST"; request.KeepAlive = false; request.ContentType = contentType; request.CookieContainer = cookieContainer; request.ContentLength = postBytes.Length; using (Stream reqStream = request.GetRequestStream()) { //LogHelper.WriteSendLog("==开始写数据=="); reqStream.Write(postBytes, 0, postBytes.Length); //LogHelper.WriteSendLog("==写入完成=="); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //在这里对接收到的页面内容进行处理 //直到request.GetResponse()程序才开始向目标网页发送post请求 Stream responseStream = response.GetResponseStream(); using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8)) { return reader.ReadToEnd(); } } } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } #endregion } }