温馨提示×

C#如何调用外部SOAP服务

c#
小樊
270
2024-06-24 11:58:33
栏目: 编程语言

在C#中调用外部SOAP服务可以使用自带的HttpClient类来发送SOAP请求。以下是一个简单的示例代码:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            string soapRequest = @"<?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:Body>
                        <YourSOAPRequestHere />
                    </soap:Body>
                </soap:Envelope>";
            
            var content = new StringContent(soapRequest, Encoding.UTF8, "text/xml");
            var response = await client.PostAsync("http://example.com/your-service", content);

            if (response.IsSuccessStatusCode)
            {
                string soapResponse = await response.Content.ReadAsStringAsync();
                Console.WriteLine(soapResponse);
            }
            else
            {
                Console.WriteLine("Error: " + response.StatusCode);
            }
        }
    }
}

在上面的示例中,首先创建一个HttpClient实例,然后定义SOAP请求的XML内容。接着使用StringContent类将SOAP请求内容转换为HttpContent对象,并通过PostAsync方法发送POST请求到指定的SOAP服务地址。最后,检查响应是否成功,并读取响应内容。

请注意,要正确构建SOAP请求的XML内容,并且需要替换<YourSOAPRequestHere />http://example.com/your-service为实际的SOAP请求和服务地址。

0