C# WINFORM 寫LINE Notify,送訊息到LINE群組中

C# WINFORM 寫LINE Notify,送訊息到LINE群組中

最重要的要先針對要發送到那個LINE群組中,建立權證

 

https://notify-bot.line.me/zh_TW/

登入LINE帳號後,就會可以選擇要發送到那個LINE群組中,建立權證

權證只會在申請中可以查看

如果不小心忘了

就重申請

 

接著是卡關很久的地方

.NET FRAMEWORK4.5.2

要用以下的CODE建立安全的SSL/TLS 的安全通道,不然會一直無法送成功

ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; // Use TLS 1.2, TLS 1.1, and TLS 1.0
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // Use TLS 1.2
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; // Bypass certificate validation

 

完整的CODE:

 public void SEND_LINE()
        {
            string token = "請改成申請的權證";
            string message = "Hello, world! "+DateTime.Now.ToString("yyyyMMddHHmmss");

            string url = "https://notify-api.line.me/api/notify";       
            try
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.DefaultConnectionLimit = 9999;
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; // Use TLS 1.2, TLS 1.1, and TLS 1.0

                var request = (HttpWebRequest)WebRequest.Create(url);
                var postData = string.Format("message={0}", message);
                var data = Encoding.UTF8.GetBytes(postData);

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                request.Headers.Add("Authorization", "Bearer " + token);

                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // Use TLS 1.2
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; // Bypass certificate validation

                using (var stream = request.GetRequestStream()) stream.Write(data, 0, data.Length);
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

 

自我LV~