C# winForm 定时访问PHP页面小工具
生活随笔
收集整理的這篇文章主要介紹了
C# winForm 定时访问PHP页面小工具
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
IDE:vs2019
項目文件:
鏈接: https://pan.baidu.com/s/1H-Q3nc6sKQbD32pp0vuQIg
提取碼: ncce?
使用場景:定時訪問本機(服務器)的某個頁面,發送參數。執行計劃任務。
界面:
?
C# 代碼:
using System; using System.Net; using System.Text; using System.Windows.Forms; using System.Web; using System.IO; using System.Text.RegularExpressions;namespace CronVisitURL {public partial class FormMain : Form{// 初始化-參數public int autoStart = 1; // 自動開始標記public int setLines = 5; // 配置信息行數public string strURL = ""; // 訪問urlpublic string strPostKey = ""; // 訪問postKeypublic string strPostData = ""; // 訪問postDatepublic int startTime = 0; // 運行時段-起始public int endTime = 0; // 運行時段-結束public Regex regex = new Regex(@"^http:\/\/(127\.0\.0\.1)|(localhost)\/"); // 訪問url,校驗規則public string iniPath = Application.StartupPath + @"\setting.ini"; // 配置文件路徑public FormMain(){InitializeComponent();}// 窗體載入后private void FormMain_Load(object sender, EventArgs e){//讀取配置信息 SetInfoRead();}// 狀態欄圖標單擊private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e){// 左鍵單擊if (e.Button == MouseButtons.Left){Show();Activate();WindowState = FormWindowState.Normal;}}// 狀態欄圖標菜單-退出private void ExitMenuItem_Click(object sender, EventArgs e){if (MessageBox.Show("你確定要退出程序嗎?", "確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK){notifyIcon1.Visible = false;Close();Dispose();Application.Exit();}}//狀態欄圖標菜單-顯示private void ShowMenuItem_Click(object sender, EventArgs e){Show();Activate();WindowState = FormWindowState.Normal;}// 按鈕-默認private void BtnDefault_Click(object sender, EventArgs e){TxbUrl.Text = "http://127.0.0.1/mws/cron/cron.php";TxbPostKey.Text = "hf_tech";TxbPostData.Text = "good";NumStartHour.Value = 0;NumStartMinute.Value = 0;NumStartSecond.Value = 0;NumEndHour.Value = 23;NumEndMinute.Value = 59;NumEndSecond.Value = 59;NumVisitRate.Value = 1;autoStart = 1;LabMsg.Text = "恢復成功";}// 按鈕-保存private void BtnSave_Click(object sender, EventArgs e){SetInfoSave();}// 按鈕-退出private void BtnExit_Click(object sender, EventArgs e){DialogResult result = MessageBox.Show("是否退出?選否,最小化到托盤", "操作提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);if (result == DialogResult.Yes){Close();Dispose();Application.Exit();}else if(result == DialogResult.No){WindowState = FormWindowState.Minimized;Visible = false;notifyIcon1.Visible = true;}}// 按鈕-隱藏private void BtnHide_Click(object sender, EventArgs e){Hide();notifyIcon1.Visible = true;}// 按鈕-暫停private void BtnPause_Click(object sender, EventArgs e){// 修改界面BtnPause.Enabled = false;BtnStart.Enabled = true;groupBox1.Enabled = true;groupBox2.Enabled = true;panel1.Enabled = true;LabMsg.Text = "定時訪問,暫停";timer1.Stop();}// 按鈕-開始private void BtnStart_Click(object sender, EventArgs e){// 初始化int visitRate = Convert.ToInt32(NumVisitRate.Value.ToString());strURL = TxbUrl.Text.Trim(); // urlstrPostKey = TxbPostKey.Text.Trim(); // PostKeystrPostData = TxbPostData.Text.Trim(); // PostData// 校驗urlif (regex.IsMatch(strURL) == false){throw new SetException("配置信息異常:訪問url,必須以本地域名或本機IP開頭");}// 校驗postif (strPostKey == ""){throw new SetException("訪問postKey,數值異常");}if (strPostData == ""){throw new SetException("訪問postData,數值異常");}// 校驗頻率if (visitRate > 3600 || visitRate < 1){throw new SetException("訪問頻率,數值異常");}// 獲取運行時段 GetRunTime();// 開始訪問 StartVist(visitRate);}// 開始訪問private void StartVist(int visitRate){// 修改界面BtnPause.Enabled = true;BtnStart.Enabled = false;groupBox1.Enabled = false;groupBox2.Enabled = false;panel1.Enabled = false;LabMsg.Text = "定時訪問,開始";// 啟動計時器timer1.Interval = visitRate * 1000; // 默認毫秒 timer1.Start();}// 計時器private void Timer1_Tick(object sender, EventArgs e){// 獲取當前時間string timeStr = DateTime.Now.ToLongTimeString().ToString();string result = Regex.Replace(timeStr, @"[^0-9]+", "");int timeNow = Convert.ToInt32(result);// 如果在運行時段內if (startTime <= timeNow && timeNow <= endTime){try{VisitURL();}catch{LabMsg.Text = "訪問失敗,請檢查后,重試";timer1.Stop();}}}// 綁定當前時間是否在運行時段內private void GetRunTime(){// 獲取運行時段string statrHour = NumStartHour.Value.ToString(); // 開始-時string statrMinute = NumStartMinute.Value.ToString(); // 開始-分string statrSecond = NumStartSecond.Value.ToString(); // 開始-秒string endHour = NumEndHour.Value.ToString(); // 結束-時string endMinute = NumEndMinute.Value.ToString(); // 結束-分string endSecond = NumEndSecond.Value.ToString(); // 結束-秒// 補零if (Convert.ToInt32(statrMinute) < 10){statrMinute = "0" + statrMinute;}if (Convert.ToInt32(statrSecond) < 10){statrSecond = "0" + statrSecond;}if (Convert.ToInt32(endMinute) < 10){endMinute = "0" + endMinute;}if (Convert.ToInt32(endSecond) < 10){endSecond = "0" + endSecond;}// 轉換string startStr = statrHour + statrMinute + statrSecond;string endStr = endHour + endMinute + endSecond;startTime = Convert.ToInt32(startStr);endTime = Convert.ToInt32(endStr);}// 訪問url-postprivate void VisitURL(){// 初始化HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);//Post請求方式request.Method = "POST";// 內容類型request.ContentType = "application/x-www-form-urlencoded";// 參數經過URL編碼string paraUrlCoded = HttpUtility.UrlEncode(strPostKey);paraUrlCoded += "=" + HttpUtility.UrlEncode(strPostData);byte[] payload;//將URL編碼后的字符串轉化為字節payload = Encoding.UTF8.GetBytes(paraUrlCoded);//設置請求的 ContentLength request.ContentLength = payload.Length;//獲得請 求流Stream writer = request.GetRequestStream();//將請求參數寫入流writer.Write(payload, 0, payload.Length);// 關閉請求流 writer.Close();// 獲得響應流HttpWebResponse response = (HttpWebResponse)request.GetResponse();StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);string responseText = reader.ReadToEnd();reader.Close();LabMsg.Text = DateTime.Now.ToLongTimeString().ToString() + ",收到數據:" + responseText;}// 自動開始-圖片private void PicAutoStart_Click(object sender, EventArgs e){// 不打勾if (autoStart == 1){PicAutoStart.Image = Properties.Resources.cb1;autoStart = 0;}// 打勾else{PicAutoStart.Image = Properties.Resources.cb2;autoStart = 1;}}// 自動開始-標簽private void LabAutoStart_Click(object sender, EventArgs e){// 不打勾if (autoStart == 1){PicAutoStart.Image = Properties.Resources.cb1;autoStart = 0;}// 打勾else{PicAutoStart.Image = Properties.Resources.cb2;autoStart = 1;}}// 配置信息-讀取private void SetInfoRead(){if (File.Exists(iniPath)){try{// 初始化-讀取數據string[] lines = File.ReadAllLines(iniPath, Encoding.UTF8); // 將文本內容轉換為數組string[] line1 = lines[1].Split(','); // postKey,Postdatastring[] line2 = lines[2].Split(','); // 開始時,分,秒string[] line3 = lines[3].Split(','); // 結束時,分,秒// 初始化-數據轉換string[] visit = new string[3];int[] cron = new int[8];visit[0] = lines[0]; // 訪問urlvisit[1] = line1[0]; // 訪問postKeyvisit[2] = line1[1]; // 訪問postDatacron[0] = Convert.ToInt32(line2[0]); // 開始-時cron[1] = Convert.ToInt32(line2[1]); // 開始-分cron[2] = Convert.ToInt32(line2[2]); // 開始-秒cron[3] = Convert.ToInt32(line3[0]); // 結束-時cron[4] = Convert.ToInt32(line3[1]); // 結束-分cron[5] = Convert.ToInt32(line3[2]); // 結束-秒cron[6] = Convert.ToInt32(lines[4]); // 訪問頻率cron[7] = Convert.ToInt32(lines[5]); // 自動開始// 初始化-數據校驗bool result = SetInfoCheck(visit, cron);if(result == true){// 賦值TxbUrl.Text = visit[0];TxbPostKey.Text = visit[1];TxbPostData.Text = visit[2];NumStartHour.Value = cron[0];NumStartMinute.Value = cron[1];NumStartSecond.Value = cron[2];NumEndHour.Value = cron[3];NumEndMinute.Value = cron[4];NumEndSecond.Value = cron[5];NumVisitRate.Value = cron[6];autoStart = cron[7];// 開啟后自動運行if (autoStart == 1){//打勾PicAutoStart.Image = Properties.Resources.cb2;// 初始化strURL = visit[0];strPostKey = visit[1];strPostData = visit[2];// 獲取運行時段 GetRunTime();// 自動開始StartVist(cron[6]);}else{// 不打勾PicAutoStart.Image = Properties.Resources.cb1;}LabMsg.Text = "配置信息,讀取成功";}}catch{LabMsg.Text = "配置信息,讀取失敗,請重新保存設置";}}else{LabMsg.Text = "配置文件,未找到,請重新保存設置";}}// 配置信息-保存private void SetInfoSave(){// 初始化string[] visit = new string[3];int[] cron = new int[8];visit[0] = TxbUrl.Text.Trim(); // 訪問urlvisit[1] = TxbPostKey.Text.Trim(); // 訪問postKeyvisit[2] = TxbPostData.Text.Trim(); // 訪問postDatacron[0] = Convert.ToInt32(NumStartHour.Value.ToString()); // 開始-時cron[1] = Convert.ToInt32(NumStartMinute.Value.ToString()); // 開始-分cron[2] = Convert.ToInt32(NumStartSecond.Value.ToString()); // 開始-秒cron[3] = Convert.ToInt32(NumEndHour.Value.ToString()); // 結束-時cron[4] = Convert.ToInt32(NumEndMinute.Value.ToString()); // 結束-分cron[5] = Convert.ToInt32(NumEndSecond.Value.ToString()); // 結束-秒cron[6] = Convert.ToInt32(NumVisitRate.Value.ToString()); // 訪問頻率cron[7] = autoStart; // 自動開始// 數據校驗bool result = SetInfoCheck(visit, cron);if (result == true){// 設置信息-字符串string str = visit[0] + Environment.NewLine;str += visit[1] + ',' + visit[2] + Environment.NewLine;str += cron[0].ToString() + ',' + cron[1].ToString() + ',' + cron[2].ToString() + Environment.NewLine;str += cron[3].ToString() + ',' + cron[4].ToString() + ',' + cron[5].ToString() + Environment.NewLine;str += cron[6].ToString() + Environment.NewLine;str += cron[7].ToString();// 寫入配置文件 File.WriteAllText(iniPath, str, Encoding.UTF8);LabMsg.Text = "配置信息,保存成功";}}// 配置數據校驗private bool SetInfoCheck(string[] visit, int[] cron){// 參數個數-訪問if(visit.GetLength(0) !=3){LabMsg.Text = "訪問參數,數值異常";return false;}// 參數個數-每日運行時段,訪問頻率,自動運行if (cron.GetLength(0) !=8){LabMsg.Text = "計時器,數值異常";return false;}// 訪問-urlif (regex.IsMatch(visit[0]) == false){LabMsg.Text = "配置信息異常:訪問url,必須以本地域名或本機IP開頭";return false;}// 訪問-postKeyif (visit[1] == ""){LabMsg.Text = "訪問postKey,數值異常";return false;}// 訪問-postDataif (visit[2] == ""){LabMsg.Text = "訪問postData,數值異常";return false;}// 開始-時if (cron[0] > 23 || cron[0] < 0){LabMsg.Text = "每日運行時段,開始小時,數值異常";return false;}// 開始-分if (cron[1] > 60 || cron[1] < 0){LabMsg.Text = "每日運行時段,開始分鐘,數值異常";return false;}// 開始-秒if (cron[2] > 60 || cron[2] < 0){LabMsg.Text = "每日運行時段,開始秒鐘,數值異常";return false;}// 結束-時if (cron[3] > 23 || cron[3] < 0){LabMsg.Text = "每日運行時段,結束小時,數值異常";return false;}// 結束-分if (cron[4] > 60 || cron[4] < 0){LabMsg.Text = "每日運行時段,結束分鐘,數值異常";return false;}// 結束-秒if (cron[5] > 60 || cron[5] < 0){LabMsg.Text = "每日運行時段,結束秒鐘,數值異常";return false;}// 訪問頻率if (cron[6] > 3600 || cron[ 6] < 1){LabMsg.Text = "訪問頻率,數值異常";return false;}// 自動開始if (cron[7] > 1 || cron[7] < 0){LabMsg.Text = "自動運行,數值異常";return false;}return true;}}// 自定義異常類class SetException : Exception{public SetException(string message) : base(message){MessageBox.Show(message);}} }// the end @nb;php 代碼:
<?php // 本腳本所有的輸出都會在觸發器狀態欄上顯示,如果輸入內容過多可能會導致觸發器崩潰// 基本設置 ignore_user_abort(true); // 忽略客戶端斷開 set_time_limit(0); // 設置執行不超時 date_default_timezone_set('Asia/Shanghai'); // 設置時區// 定時訪問 if(empty($_POST[POST_KEY]) || $_POST[POST_KEY] != POST_DATA) {die('error_post'); }//訪問者id $remote_ip = $_SERVER["REMOTE_ADDR"];//如果是本機訪問(ipv4|ipv6) if($remote_ip != '127.0.0.1' && $remote_ip != '::1') {die('error_ip'); }// do something// 輸出反饋信息給觸發器 echo $_POST[POST_KEY];// the end @nb;?
轉載于:https://www.cnblogs.com/nb08611033/p/11105631.html
總結
以上是生活随笔為你收集整理的C# winForm 定时访问PHP页面小工具的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: day05 selenium库的基础使用
- 下一篇: 哈夫曼树(最优树)及编码