using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
namespace 報到系統
{
public class BaseSMSProvider
{
///
/// 驗證手機號碼格式
///
protected static bool IsValidMobileNumber(string mobile)
{
if (string.IsNullOrEmpty(mobile))
return false;
mobile = mobile.Trim();
return System.Text.RegularExpressions.Regex.IsMatch(mobile, @"^09\d{8}$");
}
///
/// 初始化安全設定
///
protected static void InitializeSecuritySettings()
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
}
///
/// 發送 JSON POST 請求
///
//protected static string PostJson(string url, object jsonBody, Dictionary headers = null, int timeoutSeconds = 60)
//{
// var json = JsonConvert.SerializeObject(jsonBody);
// var data = Encoding.UTF8.GetBytes(json);
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// request.Method = "POST";
// request.ContentType = "application/json";
// request.ContentLength = data.Length;
// // 設定 timeout(毫秒)
// request.Timeout = timeoutSeconds * 1000;
// // 可選:設定讀取/寫入 timeout
// request.ReadWriteTimeout = timeoutSeconds * 1000;
// // 加入 headers
// if (headers != null)
// {
// foreach (var header in headers)
// {
// request.Headers.Add(header.Key, header.Value);
// }
// }
// // 寫入 request body
// using (var stream = request.GetRequestStream())
// {
// stream.Write(data, 0, data.Length);
// }
// // 取得 response
// using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
// using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
// {
// return reader.ReadToEnd();
// }
//}
protected static string PostJson(string url, object jsonBody, Dictionary headers = null, int timeoutSeconds = 60)
{
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
client.Headers.Add("Content-Type", "application/json");
if (headers != null)
{
foreach (var header in headers)
{
client.Headers.Add(header.Key, header.Value);
}
}
return client.UploadString(url, "POST", JsonConvert.SerializeObject(jsonBody));
}
}
///
/// 發送表單 POST 請求
///
protected static string PostForm(string url, NameValueCollection formData)
{
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
return Encoding.UTF8.GetString(client.UploadValues(url, "POST", formData));
}
}
}
}