SMS 的 .NET 代码

2024-04-09

HI all.

我正在编写一些代码来通过 Zeep Mobile 发送/接收短信(http://zeepmobile.com/developers/ http://zeepmobile.com/developers/).

我查看了他们的谷歌群组,甚至联系了他们的支持人员,但他们不太善于沟通,我现在真的很盲目。

我必须与它们集成(工作需要它),我不确定为什么我的代码不起作用。因此,我想知道是否有人有任何不介意共享的 C# .Net 代码,以便我可以将其集成到我的应用程序中。

当然,这取决于您是否有使用 Zeep 的经验。如果你想让我发布我的代码,我也可以这样做。让我知道。

谢谢,我真的很感谢你的帮助。

**

编辑:我已在此处添加源代码,以防任何人可以提供帮助!

**

请原谅草率的代码。这只是我为了测试 Zeep 而拼凑起来的东西,我希望有人可以尝试一下。 (.Net 3.5 控制台应用程序,以防您想要构建它)。

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Web;
using System.Web.Handlers;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;


namespace ConsoleApplication1
{


    class Program
    {
        public static string API_KEY = "MY_API_KEY";
        public static string SECRET_ACCESS_KEY = "MY_SECRET_KEY";
        public static string PATTERN_RFC1123 = "ddd, dd MMM yyyy HH:mm:ss " + "GMT";

        static void Main(string[] args)
        {
            // URL for sending message - 
            //      send_message = "https://api.zeepmobile.com/messaging/2008-07-14/send_message";
            //      blast_message = "https://api.zeepmobile.com/messaging/2008-07-14/blast_message";
            string apiurl = "https://api.zeepmobile.com/messaging/2008-07-14/blast_message";


            // FORMAT must be Sun, 06 Nov 1994 08:49:37 GMT
            string http_date = DateTime.UtcNow.ToString("r");
            // Text to send
            string body = HttpUtility.UrlEncode("Test message.", System.Text.Encoding.UTF8);
            // NOTE: Use 'user_id=22&body=' instead of just 'body=' when sending a message to a user.
            // 22 is a user I have previously registered with ZEEP and is used for testing purposes.
            string parameters = "body=" + body; 
            // String that will be converted into a signature.
            string canonicalString = API_KEY + http_date + parameters;


            //------------START HASH COMPUTATION---------------------
            // Compute the Base64 HMACSHA1 value
            HMACSHA1 hmacsha1 = new HMACSHA1(SECRET_ACCESS_KEY.ToByteArray());

            // Compute the hash of the input file.
            byte[] hashValue = hmacsha1.ComputeHash(canonicalString.ToByteArray());

            String b64Mac = hashValue.ToBase64String();
            String authentication = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);
            //-----------END HASH COMPUTATION------------------------


            // We are using TCPClient instead of an HTTPWebRequest because we need to manually
            // set the "Headers" such as Date, Authorization etc which cannot easily be done with HTTPWebRequest.
            Uri reqUrl = new Uri(apiurl);
            TcpClient client = new TcpClient(reqUrl.Host, reqUrl.Port);
            NetworkStream netStream = client.GetStream();
            // SSLStream is used for secure communication. ZEEP requires the use of SSL to send and SMS.
            System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(
                netStream, 
                false, 
                new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate));
            sslStream.AuthenticateAsClient(reqUrl.Host);


            // POST content we are going to transmit over the SSL channel. 
            // See. http://zeepmobile.com/developers/documentation/messaging/2008-07-14/rest_api#send_message
            System.IO.StreamWriter s = new System.IO.StreamWriter(sslStream);
            s.WriteLine(String.Format("POST {0} HTTP/1.1", "/api/blast"));
            s.WriteLine(String.Format("Host: {0}", "api.zeepmobile.com"));
            s.WriteLine(String.Format("Authorization: Zeep {0}:{1}", API_KEY, b64Mac));
            s.WriteLine(String.Format("Date: {0}", http_date));
            s.WriteLine(String.Format("Content-Type: {0}", "application/x-www-form-urlencoded"));
            s.WriteLine(String.Format("Content-Length: {0}", parameters.Length));
            s.WriteLine(String.Format("{0}", parameters));
            s.Flush();


            System.IO.StreamReader r = new StreamReader(sslStream);
            string resp = r.ReadToEnd();
            Console.WriteLine(resp);
            r.Close();

        }

        // The following method is invoked by the RemoteCertificateValidationDelegate.
        // We want to make sure the SSL has no Policy errors and is safe.
        public static bool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }

    }

    public static class Extensions
    {
        public static byte[] ToByteArray(this string input)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetBytes(input);
        }

        public static string ToBase64String(this byte[] input)
        {
            return Convert.ToBase64String(input);
        }
    }
}

Error

当我运行此代码时发生的情况是下图所示的错误。


解决方案:

好的。我昨晚一直在努力,取得了一些进展。我使用 Fiddler 构建 POST 消息,以查看上面的内容与服务器期望的内容之间是否存在差异。

我已经让它发送消息并返回 HTTP 200 OK 响应。再说一次,这段代码还没有准备好投入生产,它只是用来测试的,看看我是否能让 Zeep 工作。感谢所有回复的人,如果您正在寻找 ZEEP 代码,我希望这可以帮助您。


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Web;
using System.Web.Handlers;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;


namespace ConsoleApplication1
{
    class Program
    {
        public static string API_KEY = "YOUR_API_KEY_GOES_HERE! INCLUDE DASHES!";
        public static string SECRET_ACCESS_KEY = "YOUR_SECRET_KEY_GOES_HERE!";

        static void Main(string[] args)
        {
            Console.WriteLine("BLAST - \r\n\r\n");
            BlastTcpPost();

            Console.WriteLine("SEND - \r\n\r\n");
            SendTcpPost();
        }

        /// <summary>
        /// Send a BLAST to all users in your ZEEP account.
        /// </summary>
        public static void BlastTcpPost()
        {
            SendSMS(
                "https://api.zeepmobile.com/messaging/2008-07-14/blast_message",    // URL for Send_Message 
                "You are on blast",                                                 // Message to send
                string.Empty                                                        // No UserId to send.
                );
        }

        /// <summary>
        /// Send a single message to a user in your ZEEP account.
        /// </summary>
        public static void SendTcpPost()
        {
            // Note:- 22 I use for the UserId is just a user I have signed up. Yours may be different and you 
            // might want to pass that in as a parameter.

            SendSMS(
                "https://api.zeepmobile.com/messaging/2008-07-14/send_message",     // URL for Send_Message
                "You are a user...good job!",                                       // Message to send
                "22"                                                                // User Id in your system.
                );

        }

        /// <summary>
        /// Uses a TCPClient and SSLStream to perform a POST.
        /// </summary>
        /// <param name="requestUrl">URL that the POST must be directed to.</param>
        /// <param name="body">Message that is to be sent.</param>
        /// <param name="user">UserId in your Zeep System. Only required if your sending a Single Message to a User. 
        /// Otherwise, just send a string.Empty.</param>
        /// <returns>Response from the server. (although it will write the response to console)</returns>
        public static string SendSMS(string requestUrl, string body, string user)
        {
            string parameters = "";
            string requestHeaders = "";
            string responseData = "";

            // FORMAT must be Sun, 06 Nov 1994 08:49:37 GMT
            string http_date = DateTime.UtcNow.ToString("r");

            // Clean the text to send
            body = HttpUtility.UrlEncode(body, System.Text.Encoding.UTF8);

            if (user.Length > 0) parameters += "user_id=" + user + "&";
            if (body.Length > 0) parameters += "body=" + body;


            // String that will be converted into a signature.
            string canonicalString = API_KEY + http_date + parameters;


            //------------START HASH COMPUTATION---------------------
            // Compute the Base64 HMACSHA1 value
            HMACSHA1 hmacsha1 = new HMACSHA1(SECRET_ACCESS_KEY.ToByteArray());

            // Compute the hash of the input file.
            byte[] hashValue = hmacsha1.ComputeHash(canonicalString.ToByteArray());

            String b64Mac = hashValue.ToBase64String();
            String authentication = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);
            //-----------END HASH COMPUTATION------------------------


            string auth = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);


            System.Uri uri = new Uri(requestUrl);
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(uri.Host, uri.Port);
            string requestMethod = "POST " + uri.LocalPath + " HTTP/1.1\r\n";

            // Set Headers for the POST message
            requestHeaders += "Host: api.zeepmobile.com\r\n";
            requestHeaders += "Authorization: " + auth + "\r\n";
            requestHeaders += "Date: " + DateTime.UtcNow.ToString("r") + "\r\n";
            requestHeaders += "Content-Type: application/x-www-form-urlencoded\r\n";
            requestHeaders += "Content-Length: " + parameters.ToByteArray().Length + "\r\n";
            requestHeaders += "\r\n";


            // Get the data to be sent as a byte array.
            Byte[] data = System.Text.Encoding.UTF8.GetBytes(requestMethod + requestHeaders + parameters + "\r\n");
            // Send the message to the connected TcpServer.
            NetworkStream stream = client.GetStream();


            // SSL Authentication is used because the Server requires https.
            System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(
                stream,
                false,
                new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate));
            sslStream.AuthenticateAsClient(uri.Host);

            // Send the data over the SSL stream.
            sslStream.Write(data, 0, data.Length);
            sslStream.Flush();


            // Receive the TcpServer.response.
            for (int i = 0; i < 100; i++)
            {
                if (stream.DataAvailable)
                {
                    break;
                }
                System.Threading.Thread.Sleep(100);
            }

            Byte[] bytes = new byte[1024];
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            while (stream.DataAvailable)
            {
                int count = sslStream.Read(bytes, 0, 1024);
                if (count == 0)
                {
                    break;
                }
                sb.Append(System.Text.Encoding.UTF8.GetString(bytes, 0, count));
            }

            responseData = sb.ToString();
            Console.WriteLine(responseData);
            // Close everything.
            client.Close();

            return responseData;
        }



        // The following method is invoked by the RemoteCertificateValidationDelegate.
        // We want to make sure the SSL has no Policy errors and is safe.
        public static bool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
            // Somehow the cert always has PolicyErrors so I am returning true regardless.
            return true;
            //if (sslPolicyErrors == SslPolicyErrors.None)
            //    return true;

            //Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

            //// Do not allow this client to communicate with unauthenticated servers.
            //return false;
        }
    }

    public static class Extensions
    {
        public static byte[] ToByteArray(this string input)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetBytes(input);
        }

        public static string ToBase64String(this byte[] input)
        {
            return Convert.ToBase64String(input);
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SMS 的 .NET 代码 的相关文章

  • ASP.NET MVC 中的经典 ASP (C#)

    我有一个应用程序想要 最终 转换为 ASP NET MVC 我想要进行全面的服务升级 到 ASP NET 但想要使用当前的 ASP 内容来运行当前的功能 这样我就可以在对新框架进行增量升级的同时升级小部分 该站点严重依赖于不太成熟的 VB6
  • asp.net 文本框文本模式数字,仅允许数字

    我只是想知道 ASP NET 中是否有一种方法只允许文本框中的数字textmode number 当我使用这个时
  • 迭代变量并查找特定类型实例的技术

    我想迭代进程中内存中的变量 通过插件动态加载 并查找特定类型的实例 以前我可以找到特定类型 或内存中的所有类型 我可以创建类型的实例 我可以获取作为不同类型的字段包含的实例 但我无论如何都不知道只是 搜索 特定类型的实例 一种方法是使用 W
  • 向 ExpandoObject 添加方法时,“关键字 'this' 在静态属性、静态方法或静态字段初始值设定项中无效”

    我尝试向 ExpandoObject 添加一个动态方法 该方法将返回属性 动态添加 给它 但它总是给我错误 我在这里做错了什么吗 using System using System Collections Generic using Sys
  • 从多个类访问串行端口

    我正在尝试使用串行端口在 arduino 和 C 程序之间进行通信 我对 C 编程有点陌生 该程序有多种用户控制形式 每一个都需要访问串口来发送数据 我需要做的就是从每个类的主窗体中写入串行端口 我了解如何设置和写入串行端口 这是我的 Fo
  • 如何从 C# 控制器重定向到外部 url

    我使用 C 控制器作为网络服务 在其中我想将用户重定向到外部网址 我该怎么做 Tried System Web HttpContext Current Response Redirect 但没有成功 使用控制器的重定向 http msdn
  • 当前的 c++ 工作草案与当前标准有何不同

    通过搜索该标准的 PDF 版本 我最终找到了这个链接C 标准措辞草案 http www open std org jtc1 sc22 wg21 docs papers 2012 n3376 pdf从 2011 年开始 我意识到我可以购买最终
  • C 语言中 =+(等于加)是什么意思?

    我碰到 与标准相反 今天在一些 C 代码中 我不太确定这里发生了什么 我在文档中也找不到它 In ancientC 版本 相当于 它的残余物与最早的恐龙骨头一起被发现 例如 B 引入了广义赋值运算符 使用x y to add y to x
  • 在 2D 中将一个点旋转另一个点

    我想知道当一个点相对于另一个点旋转一定角度时如何计算出新的坐标 我有一个块箭头 想要将其相对于箭头底部中间的点旋转角度 theta 这是允许我在两个屏幕控件之间绘制多边形所必需的 我无法使用和旋转图像 从我到目前为止所考虑的情况来看 使问题
  • 将数据打印到文件

    我已经超载了 lt lt 运算符 使其写入文件并写入控制台 我已经为同一个函数创建了 8 个线程 并且我想输出 hello hi 如果我在无限循环中运行这个线程例程 文件中的o p是 hello hi hello hi hello hi e
  • Azure 事件中心 - 按顺序接收事件

    我使用下面的代码从 Azure Event Hub 接收事件 https learn microsoft com en us azure event hubs event hubs dotnet framework getstarted s
  • 生产代码中的 LRU 实现

    我有一些 C 代码 需要使用 LRU 技术实现缓存替换 目前我知道两种实现LRU缓存替换的方法 每次访问缓存数据时使用时间戳 最后比较替换时的时间戳 使用缓存项的堆栈 如果最近访问过它们 则将它们移动到顶部 因此最后底部将包含 LRU 候选
  • 通过 NHibernate 进行查询,无需 N+1 - 包含示例

    我有一个 N 1 问题 我不知道如何解决它 可以在这个问题的底部找到完全可重复的样本 因此 如果您愿意 请创建数据库 设置 NUnit 测试和所有附带的类 并尝试在本地消除 N 1 这是我遇到的真实问题的匿名版本 众所周知 这段代码对于帮助
  • 如何挤出平面 2D 网格并赋予其深度

    我有一组共面 连接的三角形 即二维网格 现在我需要将其在 z 轴上挤出几个单位 网格由一组顶点定义 渲染器通过与三角形数组匹配来理解这些顶点 网格示例 顶点 0 0 0 10 0 0 10 10 0 0 10 0 所以这里我们有一个二维正方
  • 当前的 x86 架构是否支持非临时加载(来自“正常”内存)?

    我知道有关此主题的多个问题 但是 我没有看到任何明确的答案或任何基准测量 因此 我创建了一个处理两个整数数组的简单程序 第一个数组a非常大 64 MB 第二个数组b很小 无法放入 L1 缓存 程序迭代a并将其元素添加到相应的元素中b在模块化
  • 什么是 __declspec 以及何时需要使用它?

    我见过这样的例子 declspec在我正在阅读的代码中 它是什么 我什么时候需要使用这个构造 这是 Microsoft 对 C 语言的特定扩展 它允许您使用存储类信息来赋予类型或函数属性 文档 declspec C https learn
  • 运算符“==”不能应用于“int”和“string”类型的操作数

    我正在编写一个程序 我想到了一个数字 然后计算机猜测了它 我一边尝试一边测试它 但我不断收到不应该出现的错误 错误是主题标题 我使用 Int Parse 来转换我的字符串 但我不知道为什么会收到错误 我知道它说 不能与整数一起使用 但我在网
  • 双精度类型二维多维数组的 pinvoke 编组作为 c# 和 c++ 之间的输入和输出

    我有以下我正在尝试解决的双物质类型的 2d 多维数组的 c 和 c pinvoke 编组 我已经查看了以下热门内容以获得我目前拥有的内容使用双精度数组进行 P Invoke 在 C 和 C 之间编组数据 https stackoverflo
  • WinRT 定时注销

    我正在开发一个 WinRT 应用程序 要求之一是应用程序应具有 定时注销 功能 这意味着在任何屏幕上 如果应用程序空闲了 10 分钟 应用程序应该注销并导航回主屏幕 显然 执行此操作的强力方法是在每个页面的每个网格上连接指针按下事件 并在触
  • Googletest:如何异步运行测试?

    考虑到一个包含数千个测试的大型项目 其中一些测试需要几分钟才能完成 如果按顺序执行 整套测试需要一个多小时才能完成 通过并行执行测试可以减少测试时间 据我所知 没有办法直接从 googletest mock 做到这一点 就像 async选项

随机推荐

  • 如何使用 SPARQL 区分事物和无生命物体

    使用 SPARQL 我可以很轻松地获取有关某些资源的所有相关信息 但我很难弄清楚如何真正区分事物和资源things 其中Thing是所有类的超类 是无生命的物体 例如杯子 勺子 铅笔等 例如 下面是 DBPedia 中的一些无生命物体 Fo
  • 如何正确使用Task.WhenAll()

    我正在尝试使用Task WhenAll等待多个任务的完成 我的代码如下 它应该启动多个异步任务 每个任务检索一条总线路线 然后将它们添加到本地数组中 然而 Task WhenAll 立即返回 本地路由数组的计数为零 这看起来很奇怪 因为我期
  • 如何从单独的进程监控应用程序崩溃

    我有一个特定的 net 应用程序 偶尔会因以下 Windows 错误之一而崩溃 application name has encountered a problem and needs to close We are sorry for t
  • 为什么标准C++库全部使用小写?

    只是好奇为什么 C 标准库使用全部小写和下划线而不是camelCase or PascalCase命名约定 就我个人而言 我发现在输入代码时后者更容易处理 但是是否有某种合法的理由使用前者 主要原因 为了保持与现有代码的兼容性 因为他们也用
  • 如何在Windows窗体中渲染化学反应? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 如何以窗口形式表示化学反应 我使用的是c 语言 可以使用以下方式表示数学公式mimetxt dll 但是化学反应呢 In short
  • 带有可点击和可编辑链接的编辑文本

    我正在使用 EditText 它在输入中采用 WebUrl 为此 我正在使用LinkMovementMethod使 EditText 中的链接可点击 问题是 如果文本的最后部分是链接 则单击任意位置都会导致 要打开的链接 我想要当我点击点击
  • C# 中的 IIF 是什么? [复制]

    这个问题在这里已经有答案了 可能的重复 c 中的 iif 等效项 https stackoverflow com questions 822810 iif equivalent in c 我有几行代码使用IIf在 VB 中 我正在尝试将此代
  • 具有 Maven 依赖的 Java ClassNotFoundException

    我正进入 状态ClassNotFoundException and NoClassDefFoundError当我尝试使用 Maven 定义的依赖项运行我的应用程序时出现异常 我将相关 jar 的 Maven 依赖项添加到了我的pom xml
  • 如何向 NextRequest 类型添加新属性?

    我正在创建一个向 NextRequest 添加 name 属性的中间件 该属性将在 API 的其他部分中使用 import NextRequest NextResponse from next server export function
  • Spring 3.1.1和Cache配置问题

    我正在测试 Spring 缓存 这是我的上下文文件
  • Laravel 属于关系

    好吧 我对模型的 belongsTo 关系有点困惑 我有一个扩展 Elogent 的 Feeds 模型 我创建了一个名为 User 的关系函数 public function user return this gt belongsTo Us
  • 如何使用Matplotlib在图形中间绘制轴

    我想画一条平行于 y 轴且位于 x 轴中间的静态垂直线 当图中平移时 这条线不应移动 我的目标是让图形中间的这条垂直线作为参考线 我将有一些其他数字 它们表示取决于 x 轴中间的 x 值的数据 该线的端点坐标在轴坐标中为 0 5 0 和 0
  • Python API从密钥服务器获取PGP公钥?

    有没有可以从公钥服务器获取 PGP 公钥的 Python API 如果您正在查询 MIT PGP 密钥服务器 您可以使用 HTTP 我选择 urllib2 和 beautiful soup http pgp mit edu extracth
  • 即使应用程序在线,也要先查询Firestore离线数据[重复]

    这个问题在这里已经有答案了 即使应用程序在线 就像我们在 Firebase 实时数据库中所做的那样 如何首先检索 查询 Firestore 离线数据 谁能帮我解决 Android 版的这个问题吗 Thanks Satish 当您连接到服务器
  • Crystal Reports XI 中正确的 ISO 周编号

    如何在 Crystal Reports XI 中获取给定日期的 ISO 8601 周数 水晶报表支持DatePart 可以为您提供给定日期的 ISO 周数的函数 NumberVar week DatePart ww date crMonda
  • 将附加模板添加到右侧边栏 magento

    我只是尝试添加额外的模板文件以在右侧栏中包含内容块 但失败了 下面是我的努力 添加到 local xml 文件中
  • 如何将文本附加到android中的edittext中?

    在我的应用程序中 我想为用户提供从列表中选择文本并附加到编辑文本中的方法 但是我找不到任何有关如何执行此操作的文档 任何帮助都会有很大帮助 谢谢 只需使用 EditText 的append 即可 参数将附加在可编辑内容的末尾
  • 如何在 anaconda python 中导入 OpenGL?

    我在 anaconda python 上使用 ipython 笔记本 但我不知道如何安装或导入 opengl 谁能帮我解决这个问题吗 我在 Linux xubuntu 上使用 anaconda 抱歉英语不好 正如 David 所指出的 Vi
  • 用javascript求解线性方程组[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 使用 JavaScript 求解线性方程组的最佳方法是什么 我想找到向量 r 的解决方案 M r b 其中 M 是矩阵 b 是向量 我知道
  • SMS 的 .NET 代码

    HI all 我正在编写一些代码来通过 Zeep Mobile 发送 接收短信 http zeepmobile com developers http zeepmobile com developers 我查看了他们的谷歌群组 甚至联系了他