HttpHelper類的調(diào)用方法詳解
本文實(shí)例為大家分享了HttpHelper類的方法使用,供大家參考,具體內(nèi)容如下
首先列出HttpHelper類
/// <summary> /// Http操作類 /// </summary> public class HttpHelper { private static log4net.ILog mLog = log4net.LogManager.GetLogger("HttpHelper"); [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData); [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool InternetGetCookie(string lpszUrlName, string lbszCookieName, StringBuilder lpszCookieData, ref int lpdwSize); public static StreamReader mLastResponseStream = null; public static System.IO.StreamReader LastResponseStream { get { return mLastResponseStream; } } private static CookieContainer mCookie = null; public static CookieContainer Cookie { get { return mCookie; } set { mCookie = value; } } private static CookieContainer mLastCookie = null; public static HttpWebRequest CreateWebRequest(string url, HttpRequestType httpType, string contentType, string data, Encoding requestEncoding, int timeout, bool keepAlive) { if (String.IsNullOrWhiteSpace(url)) { throw new Exception("URL為空"); } HttpWebRequest webRequest = null; Stream requestStream = null; byte[] datas = null; switch (httpType) { case HttpRequestType.GET: case HttpRequestType.DELETE: if (!String.IsNullOrWhiteSpace(data)) { if (!url.Contains('?')) { url += "?" + data; } else url += "&" + data; } if(url.StartsWith("https:")) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); } webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = Enum.GetName(typeof(HttpRequestType), httpType); if (contentType != null) { webRequest.ContentType = contentType; } if (mCookie == null) { webRequest.CookieContainer = new CookieContainer(); } else { webRequest.CookieContainer = mCookie; } if (keepAlive) { webRequest.KeepAlive = keepAlive; webRequest.ReadWriteTimeout = timeout; webRequest.Timeout = 60000; mLog.Info("請(qǐng)求超時(shí)時(shí)間..." + timeout); } break; default: if (url.StartsWith("https:")) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); } webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = Enum.GetName(typeof(HttpRequestType), httpType); if (contentType != null) { webRequest.ContentType = contentType; } if (mCookie == null) { webRequest.CookieContainer = new CookieContainer(); } else { webRequest.CookieContainer = mCookie; } if (keepAlive) { webRequest.KeepAlive = keepAlive; webRequest.ReadWriteTimeout = timeout; webRequest.Timeout = 60000; mLog.Info("請(qǐng)求超時(shí)時(shí)間..." + timeout); } if (!String.IsNullOrWhiteSpace(data)) { datas = requestEncoding.GetBytes(data); } if (datas != null) { webRequest.ContentLength = datas.Length; requestStream = webRequest.GetRequestStream(); requestStream.Write(datas, 0, datas.Length); requestStream.Flush(); requestStream.Close(); } break; } //mLog.InfoFormat("請(qǐng)求 Url:{0},HttpRequestType:{1},contentType:{2},data:{3}", url, Enum.GetName(typeof(HttpRequestType), httpType), contentType, data); return webRequest; } public static CookieContainer GetLastCookie() { return mLastCookie; } /// <summary> /// 設(shè)置HTTP的Cookie,以后發(fā)送和請(qǐng)求用此Cookie /// </summary> /// <param name="cookie">CookieContainer</param> public static void SetHttpCookie(CookieContainer cookie) { mCookie = cookie; } private static HttpWebRequest mLastAsyncRequest = null; public static HttpWebRequest LastAsyncRequest { get { return mLastAsyncRequest; } set { mLastAsyncRequest = value; } } /// <summary> /// 發(fā)送請(qǐng)求 /// </summary> /// <param name="url">請(qǐng)求Url</param> /// <param name="httpType">請(qǐng)求類型</param> /// <param name="contentType">contentType:application/x-www-form-urlencoded</param> /// <param name="data">請(qǐng)求數(shù)據(jù)</param> /// <param name="encoding">請(qǐng)求數(shù)據(jù)傳輸時(shí)編碼格式</param> /// <returns>返回請(qǐng)求結(jié)果</returns> public static string SendRequest(string url, HttpRequestType httpType, string contentType, string data, Encoding requestEncoding, Encoding reponseEncoding, params AsyncCallback[] callBack) { int timeout = 0; bool keepAlive = false; if (callBack != null && callBack.Length > 0 && callBack[0] != null) { keepAlive = true; timeout = 1000*60*60; mLog.Info("寫入讀取超時(shí)時(shí)間..." + timeout); } // mLog.Info("開始創(chuàng)建請(qǐng)求...."); HttpWebRequest webRequest = CreateWebRequest(url, httpType, contentType, data, requestEncoding,timeout,keepAlive); string ret = null; // mLog.Info("創(chuàng)建請(qǐng)求結(jié)束...."); if (callBack != null && callBack.Length > 0 && callBack[0] != null) { // mLog.Info("開始異步請(qǐng)求...."); mLastAsyncRequest = webRequest; webRequest.BeginGetResponse(callBack[0], webRequest); } else { // mLog.Info("開始同步請(qǐng)求...."); StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream(), reponseEncoding); ret = sr.ReadToEnd(); sr.Close(); } mLastCookie = webRequest.CookieContainer; //mLog.InfoFormat("結(jié)束請(qǐng)求 Url:{0},HttpRequestType:{1},contentType:{2},結(jié)果:{3}", url, Enum.GetName(typeof(HttpRequestType), httpType), contentType,ret); return ret; } /// <summary> /// Http上傳文件 /// </summary> public static string HttpUploadFile(string url, string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { // 設(shè)置參數(shù) HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.AllowWriteStreamBuffering = false; request.SendChunked = true; request.Method = "POST"; request.Timeout = 300000; string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機(jī)分隔線 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); int pos = path.LastIndexOf("\\"); string fileName = path.Substring(pos + 1); //請(qǐng)求頭部信息 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); request.ContentLength = itemBoundaryBytes.Length + postHeaderBytes.Length + fs.Length + endBoundaryBytes.Length; using (Stream postStream = request.GetRequestStream()) { postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); int bytesRead = 0; int arrayLeng = fs.Length <= 4096 ? (int)fs.Length : 4096; byte[] bArr = new byte[arrayLeng]; int counter = 0; while ((bytesRead = fs.Read(bArr, 0, arrayLeng)) != 0) { counter++; postStream.Write(bArr, 0, bytesRead); } postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); } //發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù) using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求 using (Stream instream = response.GetResponseStream()) { StreamReader sr = new StreamReader(instream, Encoding.UTF8); //返回結(jié)果網(wǎng)頁(yè)(html)代碼 string content = sr.ReadToEnd(); return content; } } } } public static string HttpUploadFile(string url, MemoryStream files, string fileName) { using (MemoryStream fs = files) { // 設(shè)置參數(shù) HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.AllowWriteStreamBuffering = false; request.SendChunked = true; request.Method = "POST"; request.Timeout = 300000; string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機(jī)分隔線 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //請(qǐng)求頭部信息 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); request.ContentLength = itemBoundaryBytes.Length + postHeaderBytes.Length + fs.Length + endBoundaryBytes.Length; using (Stream postStream = request.GetRequestStream()) { postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); int bytesRead = 0; int arrayLeng = fs.Length <= 4096 ? (int)fs.Length : 4096; byte[] bArr = new byte[arrayLeng]; int counter = 0; fs.Position = 0; while ((bytesRead = fs.Read(bArr, 0, arrayLeng)) != 0) { counter++; postStream.Write(bArr, 0, bytesRead); } postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); } //發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù) using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求 using (Stream instream = response.GetResponseStream()) { StreamReader sr = new StreamReader(instream, Encoding.UTF8); //返回結(jié)果網(wǎng)頁(yè)(html)代碼 string content = sr.ReadToEnd(); return content; } } } } #region public static 方法 /// <summary> /// 將請(qǐng)求的流轉(zhuǎn)化為字符串 /// </summary> /// <param name="info"></param> /// <returns></returns> public static string GetStr(Stream info) { string result = ""; try { using (StreamReader sr = new StreamReader(info, System.Text.Encoding.UTF8)) { result = sr.ReadToEnd(); sr.Close(); } } catch { } return result; } /// <summary> /// 參數(shù)轉(zhuǎn)碼 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string stringDecode(string str) { return HttpUtility.UrlDecode(HttpUtility.UrlDecode(str, System.Text.Encoding.GetEncoding("UTF-8")), System.Text.Encoding.GetEncoding("UTF-8")); } /// <summary> /// json反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public static T Deserialize<T>(string json) { try { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } catch { return default(T); } } #endregion public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // 總是接受 return true; } } public enum HttpRequestType { POST, GET, DELETE, PUT, PATCH, HEAD, TRACE, OPTIONS }
然后列出HttpHelper的調(diào)用
1、不帶參數(shù)調(diào)用
public bool ConnectServer() { try { string url = "https://i.cnblogs.com"; string xml = HttpHelper.SendRequest(url, HttpRequestType.POST, null, null, Encoding.UTF8, Encoding.UTF8); NormalResponse nr = HuaweiXMLHelper.GetNormalResponse(xml); if (nr.Code == "0") { HttpHelper.SetHttpCookie(HttpHelper.GetLastCookie()); mIsConnect = true; return true; } else { mIsConnect = false; return false; } } catch (System.Exception ex) { mIsConnect = false; return false; } }
2.帶參數(shù)調(diào)用
private bool HandleIntelligentTask(string taskId,bool bStop) { try { if (!mIsConnect) { return false; } StringBuilder sb = new StringBuilder(); sb.AppendFormat("<request>\r\n"); sb.AppendFormat("<task_id>{0}</task_id>\r\n", taskId);//<!-- task-id為調(diào)用方生成的UUID或其它串 --> sb.AppendFormat("<status>{0}</status>\r\n",bStop?0:1); sb.AppendFormat("</request>\r\n"); string xml = sb.ToString(); string url = mIAServerUrl + "/sdk_service/rest/video-analysis/handle-intelligent-analysis"; string xml2 = HttpHelper.SendRequest(url, HttpRequestType.POST, "text/plain;charset=utf-8", xml, Encoding.UTF8, Encoding.UTF8); NormalResponse nr = HuaweiXMLHelper.GetNormalResponse(xml2); if (nr.Code == "0") { return true; } else { return false; } } catch (System.Exception ex) { return false; } }
3.異步調(diào)用
private void ReStartAlarmServer(List<string> list, string alarmUrl, Thread[] listThread) { StopAlarm(alarmUrl, listThread); listThread[0]= new Thread(new ThreadStart(delegate() { try { if (!mIsConnect) { mLog.Error("未登錄!--ReStartAlarmServer-結(jié)束!"); return; } mLog.Info("ReStartAlarmServer開始報(bào)警連接...."); if (String.IsNullOrWhiteSpace(alarmUrl)) return; mLog.InfoFormat("ReStartAlarmServer請(qǐng)求報(bào)警:URL={0}", alarmUrl); string xml = "task-id=0"; string xml2 = HttpHelper.SendRequest(alarmUrl, HttpRequestType.POST, "application/x-www-form-urlencoded", xml, Encoding.UTF8, Encoding.UTF8, AlarmCallBack); mLog.Info("ReStartAlarmServer報(bào)警連接成功!"); } catch (System.Threading.ThreadAbortException ex) { mLog.Info("ReStartAlarmServer線程已人為終止!" + ex.Message, ex); } catch (System.Exception ex) { mLog.Error("ReStartAlarmServer開始報(bào)警連接失敗:" + ex.Message, ex); mLog.Info("ReStartAlarmServer開始重新報(bào)警連接...."); mTimes = 50; } finally { } })); listThread[0].IsBackground = true; listThread[0].Start(); } private void AlarmCallBack(IAsyncResult ir) { try { HttpWebRequest webRequest = (HttpWebRequest)ir.AsyncState; string salarmUrl = webRequest.Address.OriginalString; Thread[] alarmThead = dicAlarmUrls[salarmUrl]; HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(ir); Stream stream = response.GetResponseStream(); alarmThead[1]= new Thread(new ThreadStart(delegate() { try { byte[] buffer = new byte[mAlarmReadCount]; int count = 0; string strMsg = ""; int startIndex = -1; int endIndex = -1; NormalResponse res = null; DateTime dtStart = DateTime.Now; DateTime dtEnd = DateTime.Now; while (!mIsCloseAlarm) { count = stream.Read(buffer, 0, mAlarmReadCount); if (count > 0) { strMsg += Encoding.UTF8.GetString(buffer, 0, count); startIndex = strMsg.IndexOf("<response>"); endIndex = strMsg.IndexOf("</response>"); string xml = strMsg.Substring(startIndex, endIndex - startIndex + "</response>".Length); res = HuaweiXMLHelper.GetNormalResponse(xml); strMsg = strMsg.Substring(endIndex + "</response>".Length); startIndex = -1; endIndex = -1; break; } dtEnd = DateTime.Now; if ((dtEnd - dtStart).TotalSeconds > 10) { throw new Exception("連接信息未有獲取到,需要重啟報(bào)警!"); } } while (!mIsCloseAlarm) { count = stream.Read(buffer, 0, mAlarmReadCount); if (count > 0) { string temp = Encoding.UTF8.GetString(buffer, 0, count); strMsg += temp; while (strMsg.Length > 0) { if (startIndex == -1)//未發(fā)現(xiàn)第一個(gè)<task-info> { startIndex = strMsg.IndexOf("<task-info>"); if (startIndex == -1) { if (strMsg.Length >= "<task-info>".Length) { strMsg = strMsg.Substring(strMsg.Length - "<task-info>".Length); } break; } } if (startIndex >= 0) { int i = startIndex + "<task-info>".Length; int taskInfoEndIndex = strMsg.IndexOf("</task-info>", i); if (taskInfoEndIndex > 0)//必須有任務(wù)結(jié)束節(jié)點(diǎn) { i = taskInfoEndIndex + "</task-info>".Length; int i1 = strMsg.IndexOf("</attach-rules>", i);//找到軌跡節(jié)點(diǎn)結(jié)束 int i2 = strMsg.IndexOf("</alarm>", i);//找到報(bào)警節(jié)點(diǎn)結(jié)束,發(fā)現(xiàn)一條報(bào)警 if (i1 == -1 && i2 == -1)//沒有標(biāo)志結(jié)束 { break; } else if (i1 >= 0 && (i1 < i2 || i2 == -1))//找到軌跡結(jié)束節(jié)點(diǎn) { strMsg = strMsg.Substring(i1 + "</attach-rules>".Length); startIndex = -1; endIndex = -1; continue; } else if (i2 > 0 && (i2 < i1 || i1 == -1))//找報(bào)警節(jié)點(diǎn) { endIndex = i2;//找到報(bào)警節(jié)點(diǎn)結(jié)束,發(fā)現(xiàn)一條報(bào)警 string alarmXml = "<taskalarm>" + strMsg.Substring(startIndex, endIndex - startIndex + "</alarm>".Length) + "</taskalarm>"; Thread th = new Thread(new ThreadStart(delegate() { ParseAlarmXml(alarmXml); })); th.IsBackground = true; th.Start(); strMsg = strMsg.Substring(endIndex + "</alarm>".Length); startIndex = -1; endIndex = -1; continue; } } else { break; } } } } else { Console.WriteLine("##########讀取報(bào)警反饋:無"); Thread.Sleep(1000); } } } catch (System.Threading.ThreadAbortException ex) { mLog.Info("AlarmCallBack...7"); try { if (stream != null) { stream.Close(); stream.Dispose(); response.Close(); } } catch { } mLog.Info("AlarmCallBack線程已人為終止!--0" + ex.Message, ex); } catch(IOException ex) { mLog.Info("AlarmCallBack...8"); try { if (stream != null) { stream.Close(); stream.Dispose(); response.Close(); } } catch { } } catch (ObjectDisposedException ex) { mLog.Info("AlarmCallBack...9"); mLog.Info("AlarmCallBack讀取流已人為終止!--2" + ex.Message, ex); try { if (stream != null) { stream.Close(); stream.Dispose(); response.Close(); } } catch { } } catch (System.Exception ex) { mLog.Info("AlarmCallBack...10"); mLog.Error("AlarmCallBack 0:" + ex.Message,ex); try { if (stream != null) { stream.Close(); stream.Dispose(); response.Close(); } } catch { } } finally { } })); alarmThead[1].IsBackground = true; alarmThead[1].Start(); } catch (System.Exception ex) { mLog.Info("AlarmCallBack...11"); mLog.Error("AlarmCallBack 1:" + ex.Message,ex); mLog.Info("AlarmCallBack開始重新報(bào)警連接....3"); mTimes = 50; } finally { } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- C#中子類調(diào)用父類的實(shí)現(xiàn)方法
- PHP調(diào)用C#開發(fā)的dll類庫(kù)方法
- C#調(diào)用C++版本dll時(shí)的類型轉(zhuǎn)換需要注意的問題小結(jié)
- C#使用Process類調(diào)用外部exe程序
- C#使用Process類調(diào)用外部程序分解
- C#調(diào)用Java類的實(shí)現(xiàn)方法
- SQL Server中調(diào)用C#類中的方法實(shí)例(使用.NET程序集)
- C#中派生類調(diào)用基類構(gòu)造函數(shù)用法分析
- C#調(diào)用mmpeg進(jìn)行各種視頻轉(zhuǎn)換的類實(shí)例
- C#中調(diào)用VB中Inputbox類的實(shí)現(xiàn)方法
相關(guān)文章
WCF實(shí)現(xiàn)進(jìn)程間管道通信Demo分享
下面小編就為大家分享一篇WCF實(shí)現(xiàn)進(jìn)程間管道通信Demo,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12C# GetMethod方法的應(yīng)用實(shí)例講解
GetMethod 是獲取當(dāng)前 Type 的特定方法,具有多個(gè)重載, GetMethod 即使用指定的綁定約束搜索指定方法,本文給大家介紹了C# GetMethod方法的應(yīng)用實(shí)例,需要的朋友可以參考下2024-04-04C# dump系統(tǒng)lsass內(nèi)存和sam注冊(cè)表詳細(xì)
這篇文章主要介紹了C# dump系統(tǒng)lsass內(nèi)存和sam注冊(cè)表,在這里選擇 C# 的好處是體積小,結(jié)合 loadAssembly 方便免殺,希望對(duì)讀者們有所幫助2021-09-09C#在線程中訪問ui元素的幾種實(shí)現(xiàn)方法
在C#中,特別是在Windows窗體(WinForms)或WPF應(yīng)用程序中,直接從非UI線程(如后臺(tái)工作線程)訪問UI元素通常是不被允許的,如果你需要在非UI線程中更新UI元素,本文給大家介紹了C#在線程中訪問ui元素的幾種實(shí)現(xiàn)方法,需要的朋友可以參考下2024-07-07C# HttpClient Cookie驗(yàn)證解決方法
本文將詳細(xì)介紹C# HttpClient Cookie驗(yàn)證解決方法,需要了解的朋友可以參考下2012-11-11