Blame view

CsbrHcgClient/SoapClient.cs 9.34 KB
white committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace CsbrHcgClient
{

    /// <summary>
    /// SOAP辅助类
    /// </summary>
    public static class SoapHelper
    {


        //<JITSSoapHeader xmlns='http://tempuri.org/'>
        //       <AppCode>111</AppCode>
        //       <AppPassword>222</AppPassword>
        //   </JITSSoapHeader>
        /// <summary>
        /// 消息体格式
        /// </summary>
        private const String FORMAT_ENVELOPE = @"<?xml version='1.0' encoding='utf-8'?>
                <soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
                    <soap:Header>
                        <JITSSoapHeader xmlns='http://tempuri.org/'>
                            <AppCode>{3}</AppCode>
                            <AppPassword>{4}</AppPassword>
                        </JITSSoapHeader>
                    </soap:Header>
                   <soap:Body>
                    <{0} xmlns='{1}'>{2}</{0}>
                  </soap:Body>
                </soap:Envelope>";

        /// <summary>
        /// 参数格式
        /// </summary>
        private const String FORMAT_PARAMETER = "<{0}>{1}</{0}>";

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="soapAction">SOAP动作</param>
        /// <param name="soapParameters">参数集合</param>
        /// <returns>返回值</returns>
        public static String MakeEnvelope(String soapAction, params SoapParameter[] soapParameters)
        {
            string Appcode = ConfigurationManager.AppSettings["AppCode"].ToString();
            string AppPassWord = ConfigurationManager.AppSettings["AppPassword"];

            String nameSpace, methodName;

            GetNameSpaceAndMethodName(soapAction, out nameSpace, out methodName);

            return String.Format(FORMAT_ENVELOPE, methodName, nameSpace, BuildSoapParameters(soapParameters), Appcode, AppPassWord);
        }

        /// <summary>
        /// 创建SOAP参数内容
        /// </summary>
        /// <param name="soapParameters">参数集合</param>
        /// <returns>SOAP参数内容</returns>
        public static String BuildSoapParameters(IEnumerable<SoapParameter> soapParameters)
        {
            var buffer = new StringBuilder();

            foreach (var soapParameter in soapParameters)
            {
                var strContent = GetObjectContent(soapParameter.Value);
                buffer.AppendFormat(FORMAT_PARAMETER, soapParameter.Name, strContent);
            }

            return buffer.ToString();
        }

        /// <summary>
        /// 获取名称空间
        /// </summary>
        /// <param name="soapAction">SOAP动作</param>
        /// <returns>名称空间</returns>
        public static String GetNameSpace(String soapAction)
        {
            String nameSpace, methodName;

            GetNameSpaceAndMethodName(soapAction, out nameSpace, out methodName);

            return nameSpace;
        }

        /// <summary>
        /// 获取函数名称
        /// </summary>
        /// <param name="soapAction">SOAP动作</param>
        /// <returns>函数名称</returns>
        public static String GetMethodName(String soapAction)
        {
            String nameSpace, methodName;

            GetNameSpaceAndMethodName(soapAction, out nameSpace, out methodName);

            return methodName;
        }

        /// <summary>
        /// 获取名称空间和函数名称
        /// </summary>
        /// <param name="soapAction">SOAP动作</param>
        /// <param name="nameSpace">名称空间</param>
        /// <param name="methodName">函数名称</param>
        public static void GetNameSpaceAndMethodName(String soapAction, out String nameSpace, out String methodName)
        {
            nameSpace = (methodName = String.Empty);

            var index = soapAction.LastIndexOf(Path.AltDirectorySeparatorChar);
            nameSpace = soapAction.Substring(0, index + 1);
            methodName = soapAction.Substring(index + 1, soapAction.Length - index - 1);
        }

        /// <summary>
        /// 获取对象内容XML
        /// </summary>
        /// <param name="graph">图</param>
        /// <returns>对象内容XML</returns>
        public static String GetObjectContent(Object graph)
        {
            using (var memoryStream = new MemoryStream())
            {
                var graphType = graph.GetType();
                var xmlSerializer = new XmlSerializer(graphType);

                // XML序列化
                xmlSerializer.Serialize(memoryStream, graph);

                // 获取对象XML
                var strContent = Encoding.UTF8.GetString(memoryStream.ToArray());
                var xmlDocument = new XmlDocument();

                xmlDocument.LoadXml(strContent);

                // 返回对象内容XML
                var contentNode = xmlDocument.SelectSingleNode(graphType.Name);

                if (contentNode != null)
                    return contentNode.InnerXml;

                return graph.ToString();
            }
        }
    }

    /// <summary>
    /// SOAP参数
    /// </summary>
    public sealed class SoapParameter
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="value">值</param>
        public SoapParameter(String name, Object value)
        {
            this.Name = name;
            this.Value = value;
        }

        /// <summary>
        /// 名称
        /// </summary>
        public String Name { get; private set; }

        /// <summary>
        /// 值
        /// </summary>
        public Object Value { get; private set; }
    }

    /// <summary>
    /// SOAP客户端
    /// </summary>
    public sealed class SoapClient
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="uriString">请求地址</param>
        /// <param name="soapAction">SOAP动作</param>
        public SoapClient(String uriString, String soapAction)
            : this(new Uri(uriString), soapAction) { }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="uri">请求地址</param>
        /// <param name="soapAction">SOAP动作</param>
        public SoapClient(Uri uri, String soapAction)
        {
            this.Uri = uri;
            this.SoapAction = soapAction;
            this.Arguments = new List<SoapParameter>();
            this.Credentials = CredentialCache.DefaultNetworkCredentials;
        }

        /// <summary>
        /// 参数集合
        /// </summary>
        public IList<SoapParameter> Arguments { get; private set; }

        /// <summary>
        /// 身份凭证
        /// </summary>
        public ICredentials Credentials { get; set; }

        /// <summary>
        /// 请求地址
        /// </summary>
        public Uri Uri { get; set; }

        /// <summary>
        /// SOAP动作
        /// </summary>
        public String SoapAction { get; set; }

        /// <summary>
        /// 获取响应
        /// </summary>
        /// <returns>响应</returns>
        public WebResponse GetResponse()
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(this.Uri);
            webRequest.Headers.Add("SOAPAction", SoapAction);
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Method = "POST";
            webRequest.Accept = "text/xml";
            //webRequest.Credentials = this.Credentials;
            var envelope = SoapHelper.MakeEnvelope(this.SoapAction, this.Arguments.ToArray());

            // 写入请求SOAP信息
            using (var requestStream = webRequest.GetRequestStream())
            {
                using (var textWriter = new StreamWriter(requestStream))
                {
                    envelope = SoapHelper.MakeEnvelope(this.SoapAction, this.Arguments.ToArray());

                    if (!String.IsNullOrEmpty(envelope))
                        textWriter.Write(envelope);
                }
            }

            try
            {
                WebResponse response = webRequest.GetResponse();
                // 获取SOAP请求返回
                return response;
            }
            catch (Exception ex)
            { throw new Exception(ex.Message); }
        }

        /// <summary>
        /// 获取返回结果
        /// </summary>
        /// <returns>返回值</returns>
        public Object GetResult()
        {
            // 获取响应
            var webResponse = this.GetResponse();
            var xmlReader = XmlTextReader.Create(webResponse.GetResponseStream());
            var xmlDocument = new XmlDocument();

            // 加载响应XML
            xmlDocument.Load(xmlReader);

            var nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
            nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");

            var bodyNode = xmlDocument.SelectSingleNode("soap:Envelope/soap:Body", nsmgr);

            if (bodyNode.FirstChild.HasChildNodes)
                return bodyNode.FirstChild.FirstChild.InnerXml;

            return null;
        }
    }
}