C# 动态调用WebService接口教程

版权申诉
5 下载量 163 浏览量 更新于2024-09-12 收藏 77KB PDF 举报
"C#动态调用WebService接口的实现代码示例" 在C#编程中,动态调用WebService接口是常见的任务,特别是在需要与不同系统交互或者需要灵活处理多种服务调用时。本示例提供了一个名为`WebServiceCaller`的类,该类使用`System.Net.WebRequest`和`System.Net.WebResponse`来实现对WebService的动态调用。 首先,为了调用WebService,我们需要确保目标服务支持HTTP GET和POST方法。在Web.config文件中,可以添加以下配置来启用这些协议: ```xml <webServices> <protocols> <add name="HttpGet" /> <add name="HttpPost" /> </protocols> </webServices> ``` `WebServiceCaller`类的核心方法是`QueryPostWebService`,它接受三个参数:服务的URL、要调用的方法名以及一个包含参数的Hashtable。这个方法通过创建`HttpWebRequest`对象并设置其属性来构造请求,然后发送POST数据到服务。 ```csharp public static XmlDocument QueryPostWebService(string URL, string MethodName, Hashtable Pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName); request.Method = "POST"; request.ContentType = "application/soap+xml; charset=utf-8"; // 将参数转换为SOAP Envelope格式 StringBuilder sb = new StringBuilder(); sb.Append("<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/'>"); sb.Append("<soap:Body>"); foreach (DictionaryEntry entry in Pars) { sb.AppendFormat("<{0}>{1}</{0}>", entry.Key, entry.Value); } sb.Append("</soap:Body>"); sb.Append("</soap:Envelope>"); byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString()); request.ContentLength = byteArray.Length; // 写入请求体 using (Stream dataStream = request.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); } // 获取并处理响应 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) throw new ApplicationException("服务器返回错误状态码:" + response.StatusCode); using (Stream responseStream = response.GetResponseStream()) { if (responseStream == null) throw new ApplicationException("无法获取服务器响应流"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(responseStream); return xmlDoc; } } } ``` 这个方法首先构建了SOAP Envelope格式的XML字符串,将参数以键值对的形式插入到Body中。然后,将这个XML字符串写入到请求的Body中,并发送请求。当收到响应时,会检查状态码是否为200(OK),如果不是,则抛出异常。如果一切正常,它会读取响应流并将其加载到一个`XmlDocument`对象中,供后续处理使用。 此外,对于支持GET方法的服务,可以通过修改请求方式和请求内容来实现GET调用。GET请求通常将参数附加到URL中,而不是放在请求体里。 总结来说,这个C#示例提供了一种动态调用WebService接口的方式,适用于各种基于SOAP的服务。通过自定义参数集合和方法名,开发者可以轻松地与不同的WebService接口进行交互,增强了代码的灵活性和可复用性。