• 用任意语言与WebService进行交互


    using System;
    using System.Web.Services;
    using YY.SmsPlatform.Common.Objects;
    using YY.SmsPlatform.Common.UserInterface;
    using System.Configuration;
    using System.Text;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Xml;
    using System.Diagnostics;
    
    namespace YY.SmsPlatform.UserInterface
    {
        /// <summary>
        /// WebService 的摘要说明
        /// </summary>
        [WebService(Namespace = "https://dx.ipyy.net/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
        // [System.Web.Script.Services.ScriptService]
        public class WebService : System.Web.Services.WebService
        {
            /// <summary>
            /// 表示提交方式
            /// </summary>
            private const MsgOrigin msgOrigin = MsgOrigin.WebService;
            /// <summary>
            /// 请求地址
            /// </summary>
            private string _url = ConfigurationManager.AppSettings["ServerUrl"] + "webservice.asmx";
            /// <summary>
            /// 实例化WebService远程对象
            /// </summary>
            /// <summary>
            /// 发送短信接口
            /// </summary>
            /// <param name="userName">用户名</param>
            /// <param name="password">密码</param>
            /// <param name="sms">短信实体</param>
            /// <returns>发送状态</returns>
            [WebMethod(Description = "发送短信接口")]
            public SendResult SendSms(string userName, string password, SmsObject sms)
            {
                string content = SOAPMessage(userName, password, sms);
                string  rlts = GetSOAPMessage(_url, content);
                //string result =rlts.Result.Content.ReadAsStringAsync().Result;
                //SendHelper.WriteToSendXmlLog(result);
                Trace.TraceInformation(rlts);
                SendResult rlt=null;
                try
                {
                     rlt= Analysis(rlts);
                    
                }
                catch (Exception ex)
                {
    
                    Trace.TraceInformation("解析XML文件是发生错误!"+ex);
                }
                return rlt;
                
            }
            /// <summary>
            /// 解析XML文件
            /// </summary>
            /// <param name="strResult"></param>
            /// <returns></returns>
            private SendResult Analysis(string strResult)
            {
                //实例化XmlDocument
                var doc = new System.Xml.XmlDocument();
                //加载soap文件
                doc.LoadXml(strResult);
                //简化soap,XML文件
                string sendSmsResult = doc.DocumentElement["soap:Body"]["SendSmsResponse"].InnerXml;
                //重新加载简化后的xml文件
                doc.LoadXml(sendSmsResult);
                //xml 命名空间
                XmlNamespaceManager xmlns = new XmlNamespaceManager(doc.NameTable);
                //添加xml命名空间缩写
                xmlns.AddNamespace("H", "http://www.yysms.com/");
                //获取xml文件<StatusCode></StatusCode>节点下的文本值
                string payType = doc.SelectSingleNode("/H:SendSmsResult/H:PayType",xmlns).InnerText;
                string statusCode = doc.SelectSingleNode("/H:SendSmsResult/H:StatusCode", xmlns).InnerText;
    
                //PayType
                string msgid = doc.SelectSingleNode("/H:SendSmsResult/H:MsgId",xmlns).InnerText;
                string description = doc.SelectSingleNode("/H:SendSmsResult/H:Description",xmlns).InnerText;//Description
                string successCounts = doc.SelectSingleNode("/H:SendSmsResult/H:SuccessCounts",xmlns).InnerText;
                string billingCount = doc.SelectSingleNode("/H:SendSmsResult/H:BillingCount",xmlns).InnerText;
                string amount = doc.SelectSingleNode("/H:SendSmsResult/H:Amount",xmlns).InnerText;
                string balance = doc.SelectSingleNode("/H:SendSmsResult/H:Balance",xmlns).InnerText;
                string billingAmount = doc.SelectSingleNode("/H:SendSmsResult/H:BillingAmount",xmlns).InnerText;
                //用于返回的信息
                ResultCode resultCode = (ResultCode)Enum.Parse(typeof(ResultCode), statusCode);
                SendResult sendResult = new SendResult(resultCode, description, msgid, Convert.ToInt64(amount),
                    Convert.ToInt32(successCounts)) { BillingCount = Convert.ToInt32(billingCount), Balance = Convert.ToDecimal(balance), BillingAmount = Convert.ToDecimal(billingAmount) };
                //SendResult r = new SendResult(mtStatus, msgid, gatawayCode, description);
                return sendResult;
            }
            /// <summary>
            /// 包装Soap协议XML文件
            /// </summary>
            /// <param name="userName">用户名</param>
            /// <param name="password">密码</param>
            ///<param name="sms">短信内容</param>
            /// <returns></returns>
            private string SOAPMessage(string userName, string password, SmsObject sms)
            {
                var sb = new StringBuilder();
                sb.Append("<?xml version="1.0" encoding="utf-8"?>");
                sb.Append("<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">");
                sb.Append("<soap12:Body><SendSms xmlns="http://www.yysms.com/">");
                sb.AppendFormat("<userName>{0}</userName>", userName);
                sb.AppendFormat("<password>{0}</password>", password);
                sb.AppendFormat("<sms><Msisdns>{0}</Msisdns>", sms.Msisdns);
                sb.AppendFormat("<SMSContent><![CDATA[{0}]]></SMSContent>", sms.SMSContent);
                sb.AppendFormat("<ExtNumber>{0}</ExtNumber>", sms.ExtNumber);
                string planSendTime = sms.PlanSendTime == null ? null : Convert.ToDateTime(sms.PlanSendTime).ToString("yyyy-MM-ddTHH:mm:ss");
                sb.AppendFormat("<PlanSendTime xsi:nil="true">{0}</PlanSendTime></sms>", planSendTime);
                sb.Append("</SendSms></soap12:Body></soap12:Envelope>");
                return sb.ToString();
                //var sb = new StringBuilder();
                ////<?xml version="1.0" encoding="utf-8"?>
                //sb.Append("<?xml version="1.0" encoding="utf-8"?>");
                ////<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
                //sb.Append("<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">");
                ////<soap12:Body><SendSms xmlns="http://www.yysms.com/">
                //sb.Append("<soap12:Body><SendSms xmlns="http://www.yysms.com/">");
                ////<userName>string</userName>
                //sb.AppendFormat("<userName>{0}</userName>", userName);
                ////<password>string</password>
                //sb.AppendFormat("<password>{0}</password>", password);
                ////<sms><Msisdns>string</Msisdns>
                //sb.AppendFormat("<sms><Msisdns>{0}</Msisdns>", sms.Msisdns);
                ////<SMSContent>string</SMSContent>
                //sb.AppendFormat("<SMSContent><![CDATA[{0}]]></SMSContent>", sms.SMSContent);
                ////<ExtNumber>string</ExtNumber>
                //sb.AppendFormat("<ExtNumber>{0}</ExtNumber>", sms.ExtNumber);
                ////<PlanSendTime>dateTime</PlanSendTime>
                //sb.AppendFormat("<PlanSendTime>{0}</PlanSendTime></sms>", sms.PlanSendTime == null ? "null" : Convert.ToDateTime(sms.PlanSendTime).ToString("yyyy-MM-ddTHH:mm:ss"));
                ////</sms></SendSms></soap12:Body></soap12:Envelope>
                //sb.Append("</SendSms></soap12:Body></soap12:Envelope>");
                //return sb.ToString();
            }
            /// <summary>
            /// HttpClient异步请求
            /// </summary>
            /// <param name="uri"></param>
            /// <param name="content"></param>
            /// <returns></returns>
            private async Task<HttpResponseMessage> SendAsync(string uri, string content)
            {
                HttpContent strContent = new StringContent(content);
                strContent.Headers.Clear();
    
                strContent.Headers.Add("Content-Type", "application/soap+xml;charset=utf-8");//"application/soap+xml; charset=utf-8"
                //strContent.Headers.Add("Content-Length", content.Length.ToString());
                HttpClient client = new HttpClient();
    
                HttpResponseMessage task = await client.PostAsync(uri, strContent);
    
                return task;
            }
            /// <summary>
            /// 
            /// </summary>
            /// <param name="uri"></param>
            /// <param name="content"></param>
            /// <returns></returns>
            private static string GetSOAPMessage(string uri, string content)
            {
                HttpClient client = new HttpClient();
    
                HttpContent stringContent = new StringContent(content);
                stringContent.Headers.Clear();
                stringContent.Headers.Add("Content-Type", "application/soap+xml;charset=utf-8");
                //stringContent.Headers.Add("Content-Length",content.Length.ToString());
                HttpRequestMessage request = new HttpRequestMessage();
                request.Content = stringContent;
                request.Method = HttpMethod.Post;
                //request.RequestUri = new UnicodeEncoding(uri);
                request.RequestUri = new Uri(uri);
    
                var rlt = client.SendAsync(request).Result;
                return rlt.Content.ReadAsStringAsync().Result;
            }
    
        }
        public class SmsObject
        {
            /// <summary>
            /// 表示手机号,多个用逗号分开。
            /// </summary>
            public string Msisdns { get; set; }
            /// <summary>
            /// 表示短信的完整内容,拆分前。
            /// </summary>
            public string SMSContent { get; set; }
            /// <summary>
            /// 表示扩展号码
            /// </summary>
            public string ExtNumber { get; set; }
            /// <summary>
            /// 表示定时发送的时间
            /// </summary>
            public DateTime? PlanSendTime { get; set; }
    
            internal SmsParam ToSmsParam()
            {
                return new SmsParam
                {
                    Msisdns = this.Msisdns,
                    SMSContent = this.SMSContent,
                    PlanSendTime = this.PlanSendTime,
                    ExtNumber = this.ExtNumber,
                };
            }
        }
    }

    本示例为C#示例,其他语言拼接字符串的原理是一样的

  • 相关阅读:
    双11实时物流订单最佳实践
    一文理解 K8s 容器网络虚拟化
    新能源汽车太猛了,这些卡脖子技术你了解吗?
    龙蜥社区成立系统运维SIG,重磅开源sysAK系统运维工具集
    sysAK(青囊)系统运维工具集:如何实现高效自动化运维?| 龙蜥技术
    零信任策略下云上安全信息与事件管理最佳实践
    MySQL 处理重复数据
    JavaScript toFixed()、toExponential、toPrecision方法
    Nginx 安装
    spring定时任务执行两次的原因与解决方法
  • 原文地址:https://www.cnblogs.com/rengke2002/p/6215861.html
Copyright © 2020-2023  润新知