尝试创建一个C#客户端(将作为Windows服务开发),该客户端将SOAP请求发送到Web服务(并获取结果)。
从这个问题中我看到了以下代码:
protected virtual WebRequest CreateRequest(ISoapMessage soapMessage) { var wr = WebRequest.Create(soapMessage.Uri); wr.ContentType = "text/xml;charset=utf-8"; wr.ContentLength = soapMessage.ContentXml.Length; wr.Headers.Add("SOAPAction", soapMessage.SoapAction); wr.Credentials = soapMessage.Credentials; wr.Method = "POST"; wr.GetRequestStream().Write(Encoding.UTF8.GetBytes(soapMessage.ContentXml), 0, soapMessage.ContentXml.Length); return wr; } public interface ISoapMessage { string Uri { get; } string ContentXml { get; } string SoapAction { get; } ICredentials Credentials { get; } }
看起来不错,任何人都知道如何使用它,并且这是否是最佳实践?
我通常使用另一种方法来做同样的事情
using System.Xml; using System.Net; using System.IO; public static void CallWebService() { var _url = "http://xxxxxxxxx/Service1.asmx"; var _action = "http://xxxxxxxx/Service1.asmx?op=HelloWorld"; XmlDocument soapEnvelopeXml = CreateSoapEnvelope(); HttpWebRequest webRequest = CreateWebRequest(_url, _action); InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest); // begin async call to web request. IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); // suspend this thread until call is complete. You might want to // do something usefull here like update your UI. asyncResult.AsyncWaitHandle.WaitOne(); // get the response from the completed web request. string soapResult; using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) { using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) { soapResult = rd.ReadToEnd(); } Console.Write(soapResult); } } private static HttpWebRequest CreateWebRequest(string url, string action) { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Headers.Add("SOAPAction", action); webRequest.ContentType = "text/xml;charset=\"utf-8\""; webRequest.Accept = "text/xml"; webRequest.Method = "POST"; return webRequest; } private static XmlDocument CreateSoapEnvelope() { XmlDocument soapEnvelopeDocument = new XmlDocument(); soapEnvelopeDocument.LoadXml( @"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""> <SOAP-ENV:Body> <HelloWorld xmlns=""http://tempuri.org/"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""> <int1 xsi:type=""xsd:integer"">12</int1> <int2 xsi:type=""xsd:integer"">32</int2> </HelloWorld> </SOAP-ENV:Body> </SOAP-ENV:Envelope>"); return soapEnvelopeDocument; } private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) { using (Stream stream = webRequest.GetRequestStream()) { soapEnvelopeXml.Save(stream); } }