在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請求和服務地址。