通过移动的Mas接口发送短信

时间:2023-03-09 05:52:59
通过移动的Mas接口发送短信

1. 首先,需要移动公司提供的用户名、密码、服务ID、接口Url等信息。

2. 将短信信息整理成XML格式的字符串,再转为byte数组,通过POST的方式,将短信发往Mas接口。需要引用"MSXML2"组件。

注意:发往Mas接口的byte数组的编码方式需要设置为"GBK",否则收到的短信将会是乱码。

byte[] data = System.Text.Encoding.GetEncoding("GBK").GetBytes(DecodeString);

3. 实现代码如下:

     /// <summary>
/// 移动公司的Mas短信接口
/// </summary>
public class MasSerVice
{
string userID = System.Configuration.ConfigurationManager.AppSettings["userID"].ToString(); //用户名
string passWord = System.Configuration.ConfigurationManager.AppSettings["passWord"].ToString(); //密码
string serviceID = System.Configuration.ConfigurationManager.AppSettings["ServiceID"].ToString(); //服务ID
string postUrl = System.Configuration.ConfigurationManager.AppSettings["postUrl"].ToString(); //移动提供的Mas接口的Url /// <summary>
/// 准备发送的XML字符串
/// </summary>
/// <param name="userID"></param>
/// <param name="passWd"></param>
/// <param name="mobileNo">手机号码,如果有多个号码,号码之间按逗号隔开,不超过100个</param>
/// <param name="smsContent">短信内容</param>
/// <returns></returns>
public string PrepareXml(string MobileNo, string smsContent)
{
string str = String.Format("<?xml version=\"1.0\" encoding=\"GB2312\"?>" +
"<svc_init ver=\"2.0.0\">" +
"<sms ver=\"2.0.0\">" +
@"<client>
<id>{0}</id>
<pwd>{1}</pwd>
<serviceid>{2}</serviceid>
</client>
<sms_info>
<phone>{3}</phone>
<content>{4}</content>
</sms_info>
</sms>
</svc_init>", userID, passWord, serviceID, MobileNo, smsContent); return str;
} /// <summary>
/// 发送短信
/// </summary>
/// <param name="mobileNo">手机号码,如果有多个号码,号码之间按逗号隔开,不超过100个</param>
/// <param name="smsContent">短信内容</param>
/// <returns></returns>
public string MessageSend(string mobileNo, string smsContent)
{
string result = String.Empty;
string postString = PrepareXml(mobileNo.Replace(',', ',').TrimEnd(new char[] { ',' }), smsContent);
try
{
string DecodeString = postString.Replace(" ", "+"); byte[] data = System.Text.Encoding.GetEncoding("GBK").GetBytes(DecodeString);
MSXML2.ServerXMLHTTP xmlhttp = new MSXML2.ServerXMLHTTP(); xmlhttp.open("POST", postUrl, false, null, null);
xmlhttp.setRequestHeader("Content-Length", data.Length.ToString());
xmlhttp.setRequestHeader("Content-Type", "text/xml;charset=gb2312");
xmlhttp.send(data);
xmlhttp.waitForResponse(); Byte[] b = (Byte[])xmlhttp.responseBody; //返回数据 string backXml = System.Text.Encoding.GetEncoding("gb2312").GetString(b); System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
xmldoc.LoadXml(backXml);
result = xmldoc.GetElementsByTagName("retcode")[].InnerText;
} catch (Exception ex)
{
result = ex.Message;
}
return result;
}
}

4. 调用接口:

new MasService().MessageSend("", "短信内容……");

如果返回的值为"00",即表示短信已经发送成功。

附:retmesg为返回代码说明信息

retcode返回值

说明

00

提交成功

01

手机号码数量和sms_id数量不匹配

26

超过短信最大发送量

25

手机号码格式有误

24

phone,content,sms_id标签内容为空

23

sms_info标签内容为空

22

账户认证失败

21

账号信息为空

12

client标签内容为空

11

提交的内容空

14

数据库连接失败