HttpHelper類及調用

来源:http://www.cnblogs.com/sxw117886/archive/2017/06/29/7094054.html
-Advertisement-
Play Games

首先列出HttpHelper類 /// <summary> /// Http操作類 /// </summary> public class HttpHelper { private static log4net.ILog mLog = log4net.LogManager.GetLogger("Ht ...


首先列出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("請求超時時間..." + 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("請求超時時間..." + 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("請求 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>
        /// 設置HTTP的Cookie,以後發送和請求用此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>
        /// 發送請求
        /// </summary>
        /// <param name="url">請求Url</param>
        /// <param name="httpType">請求類型</param>
        /// <param name="contentType">contentType:application/x-www-form-urlencoded</param>
        /// <param name="data">請求數據</param>
        /// <param name="encoding">請求數據傳輸時編碼格式</param>
        /// <returns>返回請求結果</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("寫入讀取超時時間..." + timeout);
            }
           // mLog.Info("開始創建請求....");
            HttpWebRequest webRequest = CreateWebRequest(url, httpType, contentType, data, requestEncoding,timeout,keepAlive);
            string ret = null;
           // mLog.Info("創建請求結束....");
            if (callBack != null && callBack.Length > 0 && callBack[0] != null)
            {
               // mLog.Info("開始非同步請求....");
                mLastAsyncRequest = webRequest;
                webRequest.BeginGetResponse(callBack[0], webRequest);
            }
            else
            {
               // mLog.Info("開始同步請求....");
                StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream(), reponseEncoding);
                ret = sr.ReadToEnd();
                sr.Close();
            }
            mLastCookie = webRequest.CookieContainer;
            //mLog.InfoFormat("結束請求 Url:{0},HttpRequestType:{1},contentType:{2},結果:{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))
            {
                // 設置參數
                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"); // 隨機分隔線
                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);

                //請求頭部信息
                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);
                }

                //發送請求並獲取相應回應數據
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    //直到request.GetResponse()程式才開始向目標網頁發送Post請求
                    using (Stream instream = response.GetResponseStream())
                    {
                        StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                        //返回結果網頁(html)代碼
                        string content = sr.ReadToEnd();
                        return content;
                    }
                }
            }
        }

        public static string HttpUploadFile(string url, MemoryStream files, string fileName)
        {
            using (MemoryStream fs = files)
            {
                // 設置參數
                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"); // 隨機分隔線
                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");

                //請求頭部信息
                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);
                }

                //發送請求並獲取相應回應數據
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    //直到request.GetResponse()程式才開始向目標網頁發送Post請求
                    using (Stream instream = response.GetResponseStream())
                    {
                        StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                        //返回結果網頁(html)代碼
                        string content = sr.ReadToEnd();
                        return content;
                    }
                }
            }
        }

        #region public static 方法

        /// <summary>
        /// 將請求的流轉化為字元串
        /// </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>
        /// 參數轉碼
        /// </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
    }
View Code

然後列出HttpHelper的調用

1、不帶參數調用

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;
            }
        }
View Code

2.帶參數調用

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為調用方生成的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;
            }

        }
View Code

3.非同步調用

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-結束!");
                                    return;
                                }
                                mLog.Info("ReStartAlarmServer開始報警連接....");
                                if (String.IsNullOrWhiteSpace(alarmUrl)) return;
                                mLog.InfoFormat("ReStartAlarmServer請求報警: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報警連接成功!");
                            }
                            catch (System.Threading.ThreadAbortException ex)
                            {
                                mLog.Info("ReStartAlarmServer線程已人為終止!" + ex.Message, ex);
                            }
                            catch (System.Exception ex)
                            {
                                mLog.Error("ReStartAlarmServer開始報警連接失敗:" + ex.Message, ex);
                                mLog.Info("ReStartAlarmServer開始重新報警連接....");
                                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("連接信息未有獲取到,需要重啟報警!");
                            }
                        }
                        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)//未發現第一個<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)//必須有任務結束節點
                                        {
                                            i = taskInfoEndIndex + "</task-info>".Length;
                                            int i1 = strMsg.IndexOf("</attach-rules>", i);//找到軌跡節點結束
                                            int i2 = strMsg.IndexOf("</alarm>", i);//找到報警節點結束,發現一條報警
                                            if (i1 == -1 && i2 == -1)//沒有標誌結束
                                            {
                                                break;
                                            }
                                            else if (i1 >= 0 && (i1 < i2 || i2 == -1))//找到軌跡結束節點
                                            {
                                                strMsg = strMsg.Substring(i1 + "</attach-rules>".Length);
                                                startIndex = -1;
                                                endIndex = -1;
                                                continue;
                                            }
                                            else if (i2 > 0 && (i2 < i1 || i1 == -1))//找報警節點
                                            {
                                                endIndex = i2;//找到報警節點結束,發現一條報警
                                                string alarmXml = "<taskalarm>" + strMsg.Substring(startIndex, endIndex - startIndex + "</alarm>".Length) + "</taskalarm>";

                       

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 代碼: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; namespace SunCreate.Comba ...
  • 代碼: <Grid> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="3*" /> <ColumnDefinition Width="2*" /> <ColumnDefinition Width="2*"/> <ColumnDefin ...
  • 引用DLL: WPFToolkit WPFVisifire.Charts.dll WPFVisifire.Gauges.dll 1、柱狀圖 代碼: public void BindChart1() { List<string> colorList = new List<string>(); List ...
  • 一、擴展方法的語法 在視圖中使用擴展方法的時候 如果擴展方法定義的類在其他命名空間,需要首先引用該命名空間,才能使用該擴展方法 static class 靜態類名 { static 返回類型 擴展方法名(this 擴展的類型 對象名,[其他參數列表]) { //擴展方法代碼 } } eg1:給Str ...
  • 一。關於安裝 1.可以直接通過vs自帶的Nuget包管理器來搜索下載,直接搜索“NLog”: 註意,除了要安裝第一個之外,一定要安裝“NLog.Config”,否則無法在項目中正常使用NLog的配置文件。 二。配置NLog。 1.打開NLog.config文件,在<targets>標簽內加入對應的日 ...
  • 本文博主將從零開始,一步一步的告訴大家如何在前端用bootstrap Table插件展示一個表格 首先,要下載bootstrap Table插件所必須的js,地址:https://github.com/wenzhixin/bootstrap-table 官方文檔地址:http://bootstrap ...
  • 密碼強度有4個狀態,分別如下圖。 無密碼狀態 密碼低級狀態 密碼中級狀態 密碼高級狀態 實現的代碼主要如下: HTML代碼 <input name="password" type="PassWord" onKeyUp="CheckIntensity(this.value)"><table borde ...
  • 根據http和ftp圖片地址獲取對應圖片的縮略圖和原圖 public class GetBitmapImageClass { public BitmapSource GetImageHttp(string url,int width) { var image = new BitmapImage(); ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...