1. 程式人生 > >c#發送手機短信

c#發送手機短信

odi get serve ESS com uil mat 轉化 .com

本代碼使用網易短信平臺

同時提供:發送短信給多人,校驗驗證碼,發送通知類短信等等

        /// <summary>
        /// 發送短信
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("sendMessage")]
        public int SendCode()
        {
            string nonce = "12345";
            int templateid = 111111
;//模板id string appKey = "****************";//key string appSecret = "*******";//密碼 string mobile = "12345678901";//接收短信的手機號 String url = "https://api.netease.im/sms/sendcode.action" + string.Format("?templateid={0}&mobile={1}", templateid, mobile); TimeSpan ts
= DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1); string curTime = System.Convert.ToInt32(ts.TotalSeconds).ToString();//當前的時間戳 String checkSum = getCheckSum(appSecret, nonce, curTime);//計算並獲取CheckSum IDictionary<object, String> headers = new Dictionary<object
, String>(); headers["AppKey"] = appKey; headers["Nonce"] = nonce; headers["CurTime"] = curTime; headers["CheckSum"] = checkSum; headers["ContentType"] = "application/x-www-form-urlencoded;charset=utf-8"; int code = HttpPost(url, null, headers);//發起Http請求 return code; }
        /// <summary>
        /// 計算並獲取CheckSum
        /// </summary>
        /// <param name="appSecret"></param>
        /// <param name="nonce"></param>
        /// <param name="curTime"></param>
        /// <returns></returns>
        public String getCheckSum(String appSecret, String nonce, String curTime)
        {
            byte[] data = Encoding.Default.GetBytes(appSecret + nonce + curTime);
            byte[] result;

            SHA1 sha = new SHA1CryptoServiceProvider();
            result = sha.ComputeHash(data);//進行SHA1哈希計算,轉化成16進制字符

            return getFormattedText(result);
        }
        private String getFormattedText(byte[] bytes)
        {
            char[] HEX_DIGITS = { 0, 1, 2, 3, 4, 5,6, 7, 8, 9, a, b, c, d, e, f };
            int len = bytes.Length;
            StringBuilder buf = new StringBuilder(len * 2);
            for (int j = 0; j < len; j++)
            {
                buf.Append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
                buf.Append(HEX_DIGITS[bytes[j] & 0x0f]);
            }
            return buf.ToString();
        }
        /// <summary>
        /// 發起Http請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public int HttpPost(string url, Stream data, IDictionary<object, string> headers = null)
        {
            WebRequest request = HttpWebRequest.Create(url);
            request.Method = "POST";
            if (data != null)
                request.ContentLength = data.Length;

            if (headers != null)
            {
                foreach (var v in headers)
                {
                    if (v.Key is HttpRequestHeader)
                        request.Headers[(HttpRequestHeader)v.Key] = v.Value;
                    else
                        request.Headers[v.Key.ToString()] = v.Value;
                }
            }
            HttpWebResponse response = null;
            int code = 0;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();//獲取服務器返回的內容 流
                StreamReader reader = new StreamReader(dataStream);//打開流 以便訪問
                string responseFromServer = reader.ReadToEnd();//讀取
                ResultData result = common.JsonHelper.DeserializeJsonToObject<ResultData>(responseFromServer);//轉為json  { "code":413,"msg":"verify err","obj":1}
                code = result.code;

                reader.Close();
                dataStream.Close();
                response.Close();
            }
            catch (Exception)
            {
                return code;
            }
            return code;
        }
        class ResultData
        {
            public int code { get; set; }
            public string msg { get; set; }
            public string obj { get; set; }
        }

c#發送手機短信