在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请求和服务地址。