C# Windows服务:发送SOAP请求并接收响应
本文介绍如何创建一个C# Windows服务来发送SOAP请求并接收响应。此方法利用C#的原生功能,高效且便捷。
以下代码提供了一种替代方案:
<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); // 开始异步调用Web请求 IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); // 暂停线程,直到调用完成 asyncResult.AsyncWaitHandle.WaitOne(); 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(@"<envelope http:="" xmlns:soap-env="" xmlns:xsd="" xmlns:xsi=""><body><helloworld http:="" soap-env:encoding xmlns=""><int1 xsd:integer="" xsi:type=""></int1></helloworld></body> </envelope>"); return soapEnvelopeDocument; } private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) { using (Stream stream = webRequest.GetRequestStream()) { soapEnvelopeXml.Save(stream); } }</code>
此方法提供了一种灵活高效的发送SOAP请求并接收响应的方式,无需依赖外部库。
以上是如何创建 C# Windows 服务来发送 SOAP 请求和接收响应?的详细内容。更多信息请关注PHP中文网其他相关文章!