System.Net.Http
或 System.ServiceModel.Channels
命名空间下的类,如 HttpClient
或 SoapHttpClientProtocol
。
在C#中调用SOAP API,主要涉及到使用System.Net.Http
命名空间下的HttpClient
类来发送HTTP请求,并处理返回的XML格式数据,以下是详细的步骤和示例代码:
确保在你的C#项目中引入了以下命名空间:
using System; using System.Net.Http; using System.Xml.Linq; using System.Threading.Tasks;
创建一个HttpClient
实例,用于发送HTTP请求,建议将HttpClient
实例设为静态,以便重用。
private static readonly HttpClient client = new HttpClient();
构建一个包含SOAP请求内容的字符串,这通常包括SOAP信封、头部信息以及实际的请求体,以下是一个简化的示例:
string soapEnvelope = @"<?xml version=""1.0""?> <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> <GetData xmlns=""http://tempuri.org/""> <value>Sample Value</value> </GetData> </soap:Body> </soap:Envelope>";
在发送请求之前,需要设置请求的内容类型为text/xml
,并指定接受的数据类型。
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/xml")); client.DefaultRequestHeaders.Add("SOAPAction", "http://tempuri.org/GetData");
使用HttpClient
的PostAsync
方法发送请求,并等待响应,将响应内容转换为字符串进行处理。
async Task<string> CallSoapApiAsync(string url, string soapMessage) { var content = new StringContent(soapMessage, Encoding.UTF8, "text/xml"); HttpResponseMessage response = await client.PostAsync(url, content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); }
由于SOAP API的响应通常是XML格式,可以使用XDocument
或XmlDocument
等类来解析响应数据,以下是一个使用XDocument
解析响应的示例:
XDocument xdoc = XDocument.Parse(responseString); var result = xdoc.Descendants("GetDataResult").SingleOrDefault()?.Value; Console.WriteLine(result);
将上述步骤整合到一个完整的示例中:
using System; using System.Net.Http; using System.Xml.Linq; using System.Threading.Tasks; using System.Text; class Program { private static readonly HttpClient client = new HttpClient(); static async Task Main(string[] args) { string url = "http://example.com/api"; // SOAP API的URL string soapEnvelope = @"<?xml version=""1.0""?> <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> <GetData xmlns=""http://tempuri.org/""> <value>Sample Value</value> </GetData> </soap:Body> </soap:Envelope>"; client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/xml")); client.DefaultRequestHeaders.Add("SOAPAction", "http://tempuri.org/GetData"); string responseString = await CallSoapApiAsync(url, soapEnvelope); XDocument xdoc = XDocument.Parse(responseString); var result = xdoc.Descendants("GetDataResult").SingleOrDefault()?.Value; Console.WriteLine(result); } static async Task<string> CallSoapApiAsync(string url, string soapMessage) { var content = new StringContent(soapMessage, Encoding.UTF8, "text/xml"); HttpResponseMessage response = await client.PostAsync(url, content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } }
Q1: 如果SOAP API需要身份验证怎么办?
A1: 如果SOAP API需要身份验证,可以在HttpClient
的请求头中添加相应的认证信息,对于基本认证,可以使用AuthenticationHeaderValue
类来设置用户名和密码:
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password")));
对于其他类型的认证(如OAuth),则需要根据具体的认证机制来设置相应的请求头或参数。
Q2: 如何处理复杂的SOAP请求和响应?
A2: 对于复杂的SOAP请求和响应,可能需要构建更复杂的XML结构,并使用更强大的XML处理库(如XmlSerializer
)来序列化和反序列化数据,还可能需要处理命名空间、附件、多部分消息等复杂情况,在这种情况下,建议参考相关的文档和示例代码,以确保正确构建和解析SOAP消息。