当前位置: 代码网 > it编程>编程语言>C# > C#使用融合通信API发送手机短信息

C#使用融合通信API发送手机短信息

2024年11月25日 C# 我要评论
功能实现融合云通信服务平台,为企业提供全方位通信服务,发送手机短信是其一项核心功能,本文将讲述如何使用融合云服务api为终端手机用户发送短信信息,并使用 c# 进行实现。范例运行环境操作系统: win

功能实现

融合云通信服务平台,为企业提供全方位通信服务,发送手机短信是其一项核心功能,本文将讲述如何使用融合云服务api为终端手机用户发送短信信息,并使用 c# 进行实现。

范例运行环境

操作系统: windows server 2019 datacenter

.net版本: .netframework4.7.2 或以上

开发工具:vs2019  c#

实现范例

类设计

设计utc(融合通信)类,子类sms类实现发送短信功能,sms类设计见下表:

序号成员类型名称类型说明
1属性errormessagestring此值代表调用api时发生的任何错误信息
2属性resultjsonstring返回调用api成功后返回的结果(并不代表一定发送成功)
3属性errcodestring成功调用api后返回的错误码:0代表发送成功,其它值请参照 errmsg 值提示
4属性errmsgstring请参照 errcode属性的解释
5属性ctypestring默认值为xml(小写值),还可选择 json(小写值),这是云平台提供的两种 post 消息体的类型
6属性signstring申请云api开发者,被授权提供的签名,如【xx公司】
7属性uidstring申请云api开发者,被授权提供的用户名
8属性pwdstring申请云api开发者,被授权提供的密码
9属性desttypestring目标手机用户运营商类型:1 移动,2 联通,3电信 ,默认为 0 (通用)
10属性sendurlstring申请云api开发者,被授权提供的可调用api地址,一般会有两个地址:
post xml 消息体的请调用例如:
http://api.uctyun.cn:0000/adc_posthandler_new
post json 消息体的请调用例如:
http://api.uctyun.cn:0000/adc_posthandler_json
11属性postinfostring这是一个调试信息,返回生成的 post 消息体信息
12方法sendvoidsend方法有两个参数:
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 提交数据并获取处理结果》

到此这篇关于c#使用融合通信api发送手机短信息的文章就介绍到这了,更多相关c#发送手机短信息内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com