溫馨提示×

C#如何調(diào)用外部SOAP服務(wù)

c#
小樊
194
2024-06-24 11:58:33
欄目: 編程語言

在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ù)地址。

0