使用`System.Net.WebClient`类发送HTTP请求来调用阿里云短信API

using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace BM.BLL.Utils
{
    public class SmsHelper
    {
        public static void SendSms()
        {
            string accessKeyId = "11111";
            string accessKeySecret = "1111";
            string phoneNumber = "1111";
            string signName = "11111";
            string templateCode = "SMS_295711502";
            string templateParam = "{\"code\":\"123456\"}";

            string domain = "dysmsapi.aliyuncs.com";
            string version = "2017-05-25";
            string action = "SendSms";
            string regionId = "cn-hangzhou";

            var parameters = new Dictionary<string, string>
            {
                { "AccessKeyId", accessKeyId },
                { "Action", "SendSms" },
                { "Format", "JSON" },
                { "PhoneNumbers", "13736969112" },
                { "RegionId", "cn-hangzhou" },
                { "SignName", "鹿城招生" },
                { "SignatureMethod", "HMAC-SHA1" },
                { "SignatureNonce", Guid.NewGuid().ToString() },
                { "SignatureVersion", "1.0" },
                { "TemplateCode", "SMS_295711502" },
                { "TemplateParam", "{\"code\":\"123456\"}" },
                { "Timestamp", DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'") },
                { "Version", "2017-05-25" }//2019-09-30   
            };

            string sortedQueryString = string.Join("&", parameters.Select(kvp => $"{kvp.Key}={SpecialUrlEncode(kvp.Value)}"));

            string stringToSign = $"GET&%2F&{SpecialUrlEncode(sortedQueryString)}";

            string signature = ComputeSignature(stringToSign, accessKeySecret + "&");

            string requestUrl = $"http://{domain}/?Signature={SpecialUrlEncode(signature)}&{sortedQueryString}";


            // 发送请求
            string response = SendRequest(requestUrl);

            Console.WriteLine("SMS sent, response: " + response);
        }

        public static string SpecialUrlEncode(string value)
        {
            string encodedValue = Uri.EscapeDataString(value);
            encodedValue = encodedValue.Replace("+", "%20").Replace("*", "%2A").Replace("%7E", "~");
            return encodedValue;
        }

        static string GetSortedQueryString(NameValueCollection values)
        {
            var sortedValues = values.AllKeys.Select(key => key + "=" + Uri.EscapeDataString(values[key]));
            return string.Join("&", sortedValues.OrderBy(s => s));
        }

        static string ComputeSignature(string stringToSign, string accessKeySecret)
        {
            using (var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(accessKeySecret)))
            {
                var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
                return Convert.ToBase64String(hashBytes);
            }
        }

        static string SendRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream responseStream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("SMS sent, response: " + ex.Message);
            }
            return "";
        }

    }
}

 

posted @ 2024-04-12 14:37  shiningrise  阅读(19)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css