HttpServer服务发送与接收

using System;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;

namespace NewSouthernGridMiss
{
    class WService
    {

         /// <summary> 获取字节数组</summary>
         /// <param name="XmlNs"></param>
         /// <param name="MethodName"></param>
         /// <returns></returns>
        private static byte[] EncodeParsToSoap( string XmlNs, string MethodName)
        {
            XmlNs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + XmlNs.Replace("\0","");

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(XmlNs);
            doc.Save(MissGlobal.TempPath + MethodName + ".xml"); //保存到本地途径和文件名
            return Encoding.UTF8.GetBytes(doc.OuterXml);
        }

        public static XmlDocument QuerySoapWebService(string URL, string MethodName, string Xml)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "text/xml; charset=UTF-8";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 20000;
 

            byte[] data = EncodeParsToSoap(Xml, MethodName);

            XmlDocument document = new XmlDocument();
            try
            {
                request.ContentLength = data.Length;
                request.GetRequestStream().Write(data, 0, data.Length);//发送请求
                WebResponse sd444 = request.GetResponse();//接收响应
                document = ReadXmlResponse(request.GetResponse());
                document.Save(MissGlobal.TempPath + MethodName + "_Return.xml");//把http响应的保存到本地
            }
            catch (WebException exception)
            {
                if (exception.Response != null)
                {
                    StreamReader sr = new StreamReader(((HttpWebResponse)exception.Response).GetResponseStream(), Encoding.UTF8);
                    string ddd = sr.ReadToEnd();
                    document.LoadXml(ddd);
                    document.Save(MissGlobal.TempPath + MethodName + "_Return.xml");//把http响应的保存到本地
                    throw new Exception(document.InnerText);
                }
                else
                {
                    throw exception;
                }
            } 

            return document;
        }

        private static XmlDocument ReadXmlResponse(WebResponse response)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string xml = reader.ReadToEnd();
            reader.Close();
            XmlDocument document = new XmlDocument();
            document.LoadXml(xml);
            return document;
        }     

    }
}

评论