C# 调用 WebService 的全面指南与方法解析


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 提供的最简单方法,自动生成代理类。

实现步骤

  1. 在解决方案资源管理器中右键点击项目
  2. 选择"添加" > “服务引用”
  3. 输入 WSDL 地址并命名命名空间
  4. 点击"确定"生成代理类

代码示例

// 创建服务客户端
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);
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦幻南瓜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值