使用 C# 发送和接收 SOAP 请求
本文介绍如何创建一个 C# 客户端(开发为 Windows 服务),该客户端向 Web 服务发送 SOAP 请求并等待相应的响应。
代码详解
以下代码示例展示了如何创建 SOAP 请求及其相应的响应:
<code class="language-csharp">using System.Xml; using System.Net; using System.IO; public static void CallWebService() { string url = "http://xxxxxxxxx/Service1.asmx"; string action = "http://xxxxxxxx/Service1.asmx?op=HelloWorld"; XmlDocument soapEnvelopeXml = CreateSoapEnvelope(); HttpWebRequest webRequest = CreateWebRequest(url, action); InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest); webRequest.BeginGetResponse(null, null).AsyncWaitHandle.WaitOne(); // 开始异步调用 Web 请求。 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( //... (XML 定义已省略) return soapEnvelopeDocument; } private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) { using (Stream stream = webRequest.GetRequestStream()) { soapEnvelopeXml.Save(stream); } }</code>
在此示例中:
CreateSoapEnvelope()
创建请求的 SOAP 信封。CreateWebRequest()
使用适当的标头和配置设置 Web 请求。InsertSoapEnvelopeIntoWebRequest()
将 SOAP 信封插入请求中。BeginGetResponse()
和 EndGetResponse()
用于异步 SOAP 请求处理。另一种实现建议
另一种常见方法涉及使用 WebRequest
和 WebResponse
类:
<code class="language-csharp">protected virtual WebRequest CreateRequest(ISoapMessage soapMessage) { WebRequest 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; } }</code>
此实现提供了一种更直接的方法来处理 SOAP 请求。
以上是如何在 C# 中发送和接收 SOAP 请求?的详细内容。更多信息请关注PHP中文网其他相关文章!