目录
WebService 是一种基于网络的、分布式的模块化组件,它通过标准的 Web 协议(如 HTTP)提供服务。在 C# 中,我们有多种方式可以调用 WebService,每种方法都有其适用场景和优缺点。本文将深入探讨这些方法,并提供详细的代码示例和对比分析。
一、WebService 基础概念
WebService 是一种**服务导向架构(SOA)**的实现技术,它使用标准的 XML 格式(SOAP)进行通信,具有平台无关性和语言无关性的特点。典型的 WebService 包含以下核心组件:
- WSDL (Web Services Description Language):描述服务的接口
- SOAP (Simple Object Access Protocol):通信协议
- UDDI (Universal Description, Discovery, and Integration):服务注册与发现
二、C# 调用 WebService 的主要方法
1. 添加服务引用 (Service Reference)
这是 Visual Studio 提供的最简单方法,自动生成代理类。
实现步骤:
- 在解决方案资源管理器中右键点击项目
- 选择"添加" > “服务引用”
- 输入 WSDL 地址并命名命名空间
- 点击"确定"生成代理类
代码示例:
// 创建服务客户端
var client = new MyWebServiceReference.MyWebServiceSoapClient();
try
{
// 调用服务方法
string result = client.GetData(123);
Console.WriteLine("服务返回: " + result);
}
catch (Exception ex)
{
Console.WriteLine("调用失败: " + ex.Message);
}
finally
{
// 关闭连接
if (client.State != System.ServiceModel.CommunicationState.Faulted)
{
client.Close();
}
else
{
client.Abort();
}
}
2. WebClient 类
适用于简单的 HTTP 请求,不支持 SOAP 协议。
代码示例:
using System.Net;
using System.Text;
string url = "http://example.com/webservice";
string soapEnvelope = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<GetData xmlns=""http://tempuri.org/"">
<value>123</value>
</GetData>
</soap:Body>
</soap:Envelope>";
using (WebClient webClient = new WebClient())
{
webClient.Headers.Add("Content-Type", "text/xml;charset=utf-8");
webClient.Headers.Add("SOAPAction", "http://tempuri.org/GetData");
string response = webClient.UploadString(url, soapEnvelope);
Console.WriteLine("响应内容: " + response);
}
3. HttpClient 类 (.NET 4.5+)
现代 HTTP 客户端,支持异步操作。
代码示例:
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public async Task CallWebServiceAsync()
{
string url = "http://example.com/webservice";
string soapEnvelope = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<GetData xmlns=""http://tempuri.org/"">
<value>123</value>
</GetData>
</soap:Body>
</soap:Envelope>";
using (HttpClient httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Post, url))
{
request.Content = new StringContent(soapEnvelope, Encoding.UTF8, "text/xml");
request.Headers.Add("SOAPAction", "http://tempuri.org/GetData");
using (var response = await httpClient.SendAsync(request))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("响应内容: " + responseBody);