目录
功能实现
融合云通信服务平台,为企业提供全方位通信服务,发送手机短信是其一项核心功能,本文将讲述如何使用融合云服务API为终端手机用户发送短信信息,并使用 C# 进行实现。
范例运行环境
操作系统: Windows Server 2019 DataCenter
.net版本: .netFramework4.7.2 或以上
开发工具:VS2019 C#
实现范例
类设计
设计UTC(融合通信)类,子类SMS类实现发送短信功能,SMS类设计见下表:
序号 | 成员类型 | 名称 | 类型 | 说明 |
---|---|---|---|---|
1 | 属性 | ErrorMessage | string | 此值代表调用API时发生的任何错误信息 |
2 | 属性 | ResultJson | string | 返回调用API成功后返回的结果(并不代表一定发送成功) |
3 | 属性 | errcode | string | 成功调用API后返回的错误码:0代表发送成功,其它值请参照 errmsg 值提示 |
4 | 属性 | errmsg | string | 请参照 errcode属性的解释 |
5 | 属性 | cType | string | 默认值为xml(小写值),还可选择 json(小写值),这是云平台提供的两种 POST 消息体的类型 |
6 | 属性 | sign | string | 申请云API开发者,被授权提供的签名,如【XX公司】 |
7 | 属性 | uid | string | 申请云API开发者,被授权提供的用户名 |
8 | 属性 | pwd | string | 申请云API开发者,被授权提供的密码 |
9 | 属性 | desttype | string | 目标手机用户运营商类型:1 移动,2 联通,3电信 ,默认为 0 (通用) |
10 | 属性 | sendUrl | string | 申请云API开发者,被授权提供的可调用API地址,一般会有两个地址: POST XML 消息体的请调用例如: http://api.uctyun.cn:0000/adc_posthandler_new POST JSON 消息体的请调用例如: |
11 | 属性 | postInfo | string | 这是一个调试信息,返回生成的 POST 消息体信息 |
12 | 方法 | send | void | send方法有两个参数: 1:string phoneNumber (手机号) 2:string msgContent (要发送的消息) 本方法无返回类型,返回值均返写到 ErrorMessage / ResultJson / errcode / errmsg / postInfo 属性值上 |
类代码实现
实现代码如下:
public class UTC
{
public class SMS
{
public string ErrorMessage = "";
public string ResultJson = "";
public string errcode = "";
public string errmsg = "";
public string cType = "xml";
public string sign { get; set; }
public string uid { get; set; }
public string pwd { get; set; }
public string desttype { get; set; }
public string sendUrl { get; set; }
public string postInfo = "";
public SMS() {
desttype = "0";
}
public void send(string phoneNumber, string msgContent) {
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(msgContent + sign);
string base64msg = System.Convert.ToBase64String(bytes);
string[] headers = new string[3];
headers[0] = "Connection:close";
headers[1] = "Content-Type:text/" + cType + ";charset=utf-8";
headers[2] = "Action:\"submitreq\"";
string postData = "{\"user\":\"" + uid + "\",\"password\":\"" + pwd + "\",\"submit\":[" +
"{\"srctermid\":\"\"," +
"\"desttermid\":\"" + phoneNumber + "\",\"msgcontent\":\"" + base64msg + "\"," +
"\"usermsgid\":\"" + msgid + "\"," +
"\"desttype\":\"" + desttype + "\"}]}";
if (cType == "xml")
{
string xmlData = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Body>" +
"<user>" + uid + "</user><password>" + pwd + "</password>" +
"<version>1.2</version><submit><usermsgid>" + msgid + "</usermsgid><desttermid>" +
phoneNumber + "</desttermid><srctermid></srctermid><msgcontent>" + base64msg
+ "</msgcontent><signid>0</signid><desttype>" + desttype + "</desttype><needreply>1</needreply>" +
"</submit></Body> ";
postData = xmlData;
}
postInfo = postData;
ErrorMessage = "";
ResultJson = "";
errcode = "";
errmsg = "";
string rs=GetResponseResult(sendUrl, Encoding.UTF8, "POST", postData, headers);
ErrorMessage = ws.ErrorMessage;
ResultJson = rs;
if (ErrorMessage == "" && ResultJson != "")
{
if (cType == "xml")
{
string[] rv_xml = GetBetweenStr(rs, "<result>", "</result>").Split(':');
errcode = rv_xml[0];
if (rv_xml.Length>1)
{
errmsg = rv_xml[1];
}
}
else if (cType == "json")
{
try
{
Newtonsoft.Json.Linq.JObject jsonObj = Newtonsoft.Json.Linq.JObject.Parse(rs);
string[] rv = jsonObj["result"].ToString().Split(':');
errcode = rv[0];
if (rv.Length > 1)
{
errmsg = rv[1];
}
}
catch (Exception e)
{
ErrorMessage += "\r\n" + e.Message;
ResultJson = rs;
}
}
}
}
public string GetBetweenStr(string wholestr,string beginstr,string endstr)
{
string _temp="";
if (beginstr == null && endstr == null) return "";
int _start=(beginstr==null?0:wholestr.IndexOf(beginstr,0));
if (_start == -1)
{
return "";
}
if (beginstr == null)
{
beginstr = "";
if (wholestr.IndexOf(endstr, 0) == -1)
{
return "";
}
}
if (endstr != null)
{
int _end = wholestr.IndexOf(endstr,_start+beginstr.Length);
if ((_end - _start - beginstr.Length > 0) && (_end > _start))
{
_temp = wholestr.Substring(_start + beginstr.Length, _end - _start - beginstr.Length);
}
}
else
{
if (wholestr.IndexOf(beginstr, 0) == -1)
{
return "";
}
int _end = wholestr.Length;
if ((_end - _start - beginstr.Length > 0) && (_end > _start))
{
_temp = wholestr.Substring(_start + beginstr.Length, _end - _start - beginstr.Length);
}
}
return _temp;
}
}
}
调用范例
示例代码如下:
UTC.SMS utcsms = new UTC.SMS();
utcsms.cType = "xml"; //设置为 POST XML 消息体类型
utcsms.uid = "888888";
utcsms.pwd = "TJ999999";
utcsms.sign = "【XX公司】";
utcsms.sendUrl = "http://api.uctyun.cn:0000/adc_posthandler_new";
//utcsms.sendUrl = "http://api.uctyun.cn:0000/adc_posthandler_json"; //如果是JSON请访问这个类型的API 地址
//发送短信,提供手机号和短信息内容
utcsms.send("13899999999", "融合通信提醒您,您正在执行登录操作,验证码:12345678");
string debug = string.Format("API:errcode:{4}\r\nerrmsg:{5}\r\n{3}\r\nErrMessage:{0}\r\nResultJson:{1}\r\nPostInfo:{2}", utcsms.ErrorMessage, utcsms.ResultJson, utcsms.postInfo, utcsms.sendUrl,utcsms.errcode,utcsms.errmsg);
总结
GetResponseResult 方法本次得到了更新,主要包括消息头的 Connection 名称,在 C#中使用 request.KeepAlive= Value == "close"?false : true; 的写法来实现。更新后的代码如下:
public string GetResponseResult(string url, System.Text.Encoding encoding, string method, string postData,string[] headers,string ContentType= "application/x-www-form-urlencoded",bool secValid=true)
{
method = method.ToUpper();
if (secValid == false)
{
ServicePointManager.ServerCertificateValidationCallback = validSecurity;
}
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
if (method == "GET")
{
try
{
WebRequest request2 = WebRequest.Create(@url);
request2.Method = method;
WebResponse response2 = request2.GetResponse();
Stream stream = response2.GetResponseStream();
StreamReader reader = new StreamReader(stream, encoding);
string content = reader.ReadToEnd();
return content;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return "";
}
}
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
byte[] data = encoding.GetBytes(postData);
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = method;
request.Timeout = 1000000;
if (headers != null)
{
for(int i = 0; i < headers.GetLength(0); i++)
{
if (headers[i].Split(':').Length <2)
{
continue;
}
if (headers[i].Split(':').Length > 1) {
if (headers[i].Split(':')[0] == "Host") {
request.Host = headers[i].Split(':')[1];
continue;
}else if (headers[i].Split(':')[0] == "Content-Type")
{
request.ContentType = headers[i].Split(':')[1];
continue;
}
else if (headers[i].Split(':')[0] == "Connection")
{
request.KeepAlive= headers[i].Split(':')[1]== "close"?false : true;
continue;
}
}
request.Headers.Add(headers[i]);
}
}
request.ContentType = ContentType;
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
sr.Close();
sr.Dispose();
return content;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return "";
}
}//get response result
更多介绍请参阅我的文章:《C# 实现访问 Web API Url 提交数据并获取处理结果》
融合通信官网首页请访问:https://www.uctyun.cn/
技术开发文档请访问:https://www.uctyun.cn/jswd.html
感谢您的阅读,希望本文能够对您有所帮助。
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » C#版使用融合通信API发送手机短信息
发表评论 取消回复