用C#WebClient+Server酱写一个监听网站通知的功能

Server酱:https://sc.ftqq.com/3.version
功能:往 http://sc.ftqq.com/SCKEY.send 发GET请求,就可以在微信里收到消息。
用C#WebClient+Server酱写一个监听网站通知的功能_第1张图片

using System;
using System.Text;
using System.Net;
using System.Threading;

class DownloadStringTest
{
  
    static void Main(string[] args)
    {	
    	int times = 0;//对比次数
    	string url = "http://jwb.xujc.com/tzgg/list.htm";//监控网址
	string url_1 = "https://sc.ftqq.com/SCUf.send?text=学校教务网有新通";//server酱服务:往绑定微信发送信息

        string dataSource = DownloadString(url);//获取监控网址指定的通知字符串
        
        Thread t = new Thread(Run) { IsBackground = false };//创建线程
	t.Start();//启动线程
	    
        while(true)
        {
	    	Thread.Sleep(60000);//每过六十秒运行一次

	    	string newDataSource = DownloadString(url);//六十秒后再次换取新的通知字符串
	    	times++;//计数++
	    	Console.WriteLine( "Running...Times:" + times );//提示信息
	    	
	    	if(dataSource != newDataSource )//对比六十秒前后的通知字符串
	    	{
	    		dataSource = newDataSource;//前后字符串不同,则刷新旧通知字符串
	    		Console.WriteLine( "学校教务网有新通知!" );//提示信息
	    		
        		WebClient client = new WebClient();//创建WebClient对象
			var clientText = client.DownloadData(url_1); //取网页源码,启用server酱服务
			Console.WriteLine( Encoding.GetEncoding("UTF-8").GetString(clientText) );  //编码转换,输出状态
	    	}
        }
    }
    
    public static void Run()
  {
    	Console.WriteLine( "Begin" );//提示信息
  }
	    
    public static string FindString(string text)//找到通知栏第一项到第二项字符串,并返回
    {
    	string strStart = "list_item i1";
    	int strLength = strStart.Length;
    	string str = text.Substring(text.IndexOf("list_item i1")+strLength,text.IndexOf("list_item i3")-text.IndexOf("list_item i1")-strLength);
	return str;
    }
    
    public static string DownloadString(string url)//取网页源码,编码转换,调用FindString()
    {
	try
	 {
		var client = new WebClient();
		var clientText = client.DownloadData(url); //取网页源码
		var text = Encoding.GetEncoding("UTF-8").GetString(clientText); //编码转换
		string str = FindString( text );
		return str;
	}
	catch (Exception e)
	{
		return e.ToString();
	}
    }
}

你可能感兴趣的:(C#)