在C#中調(diào)用外部SOAP服務(wù)可以使用自帶的HttpClient
類來發(fā)送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);
}
}
}
}
在上面的示例中,首先創(chuàng)建一個HttpClient
實例,然后定義SOAP請求的XML內(nèi)容。接著使用StringContent
類將SOAP請求內(nèi)容轉(zhuǎn)換為HttpContent
對象,并通過PostAsync
方法發(fā)送POST請求到指定的SOAP服務(wù)地址。最后,檢查響應(yīng)是否成功,并讀取響應(yīng)內(nèi)容。
請注意,要正確構(gòu)建SOAP請求的XML內(nèi)容,并且需要替換<YourSOAPRequestHere />
和http://example.com/your-service
為實際的SOAP請求和服務(wù)地址。