C#动态webservice调用接口
1 using System;
2 using System.Collections;
3 using System.IO;
4 using System.Net;
5 using System.Text;
6 using System.Xml;
7 using System.Xml.Serialization;
8 namespace Hishop.Plugins
9 {
10 /// <summary>
11 /// 利用WebRequest/WebResponse进行WebService调用的类
12 /// </summary>
13 public class WebServiceCaller
14 {
15 #region Tip:使用说明
16 //webServices 应该支持Get和Post调用,在web.config应该增加以下代码
17 //<webServices>
18 // <protocols>
19 // <add name="HttpGet"/>
20 // <add name="HttpPost"/>
21 // </protocols>
22 //</webServices>
23
24 //调用示例:
25 //Hashtable ht = new Hashtable(); //Hashtable 为webservice所需要的参数集
26 //ht.Add("str", "test");
27 //ht.Add("b", "true");
28 //XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx", "HelloWorld", ht);
29 //MessageBox.Show(xx.OuterXml);
30 #endregion
31
32 /// <summary>
33 /// 需要WebService支持Post调用
34 /// </summary>
35 public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
36 {
37 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
38 request.Method = "POST";
39 request.ContentType = "application/x-www-form-urlencoded";
40 SetWebRequest(request);
41 byte[] data = EncodePars(Pars);
42 WriteRequestData(request, data);
43 return ReadXmlResponse(request.GetResponse());
44 }
45
46 /// <summary>
47 /// 需要WebService支持Get调用
48 /// </summary>
49 public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
50 {
51 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
52 request.Method = "GET";
53 request.ContentType = "application/x-www-form-urlencoded";
54 SetWebRequest(request);
55 return ReadXmlResponse(request.GetResponse());
56 }
57
58 /// <summary>
59 /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
60 /// </summary>
61 public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
62 {
63 if (_xmlNamespaces.ContainsKey(URL))
64 {
65 return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
66 }
67 else
68 {
69 return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
70 }
71 }
72
73 private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
74 {
75 _xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率
76 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
77 request.Method = "POST";
78 request.ContentType = "text/xml; charset=utf-8";
79 request.Headers.Add("SOAPAction", """ + XmlNs + (XmlNs.EndsWith("/") ? "" :