C# Winform 程序中动态调用 WebService 方法

在 C# Winform 程序开发中,动态调用 WebService 方法是一种常见的需求。实现这种功能,主要依赖于反射机制和 XML 处理技术。以下介绍两种常用的方法:

方法一:使用 WebServCaller.cs 类

该方法通过构建 SOAP 请求消息,并利用 HTTP 协议发送至 WebService 服务器端,最终解析返回的 XML 数据。

代码示例:

// 创建参数哈希表
Hashtable ht = new Hashtable();
ht.Add("str", "test");
ht.Add("b", "true");

// 调用 WebService 方法
XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx", "HelloWorld", ht);

// 显示返回结果
MessageBox.Show(xx.OuterXml);

方法二:使用 WebServicesHelper.cs 类

该方法封装了 SOAP 请求和响应的细节,开发者只需传入必要的参数即可。

代码示例:

// 定义 WebService 地址和方法参数
string url = "http://www.webservicex.net/globalweather.asmx";
string[] args = new string[2];
args[0] = "Hangzhou";
args[1] = "China";

// 调用 WebService 方法
object result = WebServiceHelper.InvokeWebService(url, "GetWeather", args);

// 显示返回结果
Response.Write(result.ToString());

两种方法各有优劣,开发者可根据实际情况选择合适的方法。

zip 文件大小:4.2KB