动态调用WebService

原文参考:

https://www.cnblogs.com/shuajing/p/8694271.html

http://www.cnblogs.com/cyrix/articles/1834099.html

WebClient

 1 public  class WebServiceHelper
 2     {
 3         #region 动态调用WebService动态调用地址
 4         /// < summary>           
 5         /// 动态调用web服务         
 6         /// </summary>          
 7         /// < param name="url">WSDL服务地址< /param> 
 8         /// < param name="methodname">方法名< /param>           
 9         /// < param name="args">参数< /param>           
10         /// < returns>< /returns>          
11         public static object InvokeWebService(string url, string methodname, object[] args,params Type[] types)
12         {
13             return WebServiceHelper.InvokeWebService(url, null, methodname, args, types);
14         }
15         /// <summary>
16         /// 动态调用web服务
17         /// </summary>
18         /// <param name="url">WSDL服务地址</param>
19         /// <param name="classname">服务接口类名</param>
20         /// <param name="methodname">方法名</param>
21         /// <param name="args">参数值</param>
22         /// <returns></returns>
23         public static object InvokeWebService(string url, string classname, string methodname, object[] args, params Type[] types)
24         {
25 
26             string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
27             if ((classname == null) || (classname == ""))
28             {
29                 classname = WebServiceHelper.GetWsClassName(url);
30             }
31             try
32             {
33 
34                 //获取WSDL   
35                 WebClient wc = new WebClient();
36                 Stream stream = wc.OpenRead(url + "?WSDL");
37                 ServiceDescription sd = ServiceDescription.Read(stream);
38                 //注意classname一定要赋值获取 
39                 classname = sd.Services[0].Name;
40 
41                 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
42                 sdi.AddServiceDescription(sd, "", "");
43                 CodeNamespace cn = new CodeNamespace(@namespace);
44 
45                 //生成客户端代理类代码          
46                 CodeCompileUnit ccu = new CodeCompileUnit();
47                 ccu.Namespaces.Add(cn);
48                 sdi.Import(cn, ccu);
49                 CSharpCodeProvider icc = new CSharpCodeProvider();
50 
51 
52                 //设定编译参数                 
53                 CompilerParameters cplist = new CompilerParameters();
54                 cplist.GenerateExecutable = false;
55                 cplist.GenerateInMemory = true;
56                 cplist.ReferencedAssemblies.Add("System.dll");
57                 cplist.ReferencedAssemblies.Add("System.XML.dll");
58                 cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
59                 cplist.ReferencedAssemblies.Add("System.Data.dll");
60                 //编译代理类                 
61                 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
62                 if (true == cr.Errors.HasErrors)
63                 {
64                     System.Text.StringBuilder sb = new System.Text.StringBuilder();
65                     foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
66                     {
67                         sb.Append(ce.ToString());
68                         sb.Append(System.Environment.NewLine);
69                     }
70                     throw new Exception(sb.ToString());
71                 }
72                 //生成代理实例,并调用方法                 
73                 System.Reflection.Assembly assembly = cr.CompiledAssembly;
74                 Type t = assembly.GetType(@namespace + "." + classname, true, true);
75                 object obj = Activator.CreateInstance(t);
76                 System.Reflection.MethodInfo mi = null;
77                 if (types.Length == 0)
78                     mi = t.GetMethod(methodname);
79                 else
80                     mi = t.GetMethod(methodname, types);
81                 return mi.Invoke(obj, args);
82 
83             }
84             catch (Exception ex)
85             {
86                 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
87                 // return "Error:WebService调用错误!" + ex.Message;
88             }
89         }
90         private static string GetWsClassName(string wsUrl)
91         {
92             string[] parts = wsUrl.Split('/');
93             string[] pps = parts[parts.Length - 1].Split('.');
94             return pps[0];
95         }
96         #endregion
97     }
1 object[] a = new object[3];
2 Type[] type = new Type[] { Type.GetType("System.Int32"), Type.GetType("System.Int32"), Type.GetType("System.Int32&") };
3 a[0] = (5);
4 a[1] = (6);
5 a[2] = 0;
6 
7  object result = WebServiceHelper.InvokeWebService("http://localhost:58271/WebService1.asmx", "Sum", a,type);

Soap

  1 using System;
  2 using System.Web;
  3 using System.Xml;
  4 using System.Collections;
  5 using System.Net;
  6 using System.Text;
  7 using System.IO;
  8 using System.Xml.Serialization;
  9 
 10 //By huangz 2008-3-19
 11 
 12 /**//// <summary>
 13 ///  利用WebRequest/WebResponse进行WebService调用的类,By 同济黄正 http://hz932.ys168.com 2008-3-19
 14 /// </summary>
 15 public class WebSvcCaller
 16 {
 17     //<webServices>
 18     //  <protocols>
 19     //    <add name="HttpGet"/>
 20     //    <add name="HttpPost"/>
 21     //  </protocols>
 22     //</webServices>
 23 
 24     private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
 25 
 26     /**//// <summary>
 27     /// 需要WebService支持Post调用
 28     /// </summary>
 29     public static XmlDocument QueryPostWebService(String URL , String MethodName , Hashtable Pars)
 30     {
 31         HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
 32         request.Method = "POST";
 33         request.ContentType = "application/x-www-form-urlencoded";
 34         SetWebRequest(request);
 35         byte[] data = EncodePars(Pars);
 36         WriteRequestData(request , data);
 37 
 38         return ReadXmlResponse(request.GetResponse());
 39     }
 40     /**//// <summary>
 41     /// 需要WebService支持Get调用
 42     /// </summary>
 43     public static XmlDocument QueryGetWebService(String URL , String MethodName , Hashtable Pars)
 44     {
 45         HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
 46         request.Method = "GET";
 47         request.ContentType = "application/x-www-form-urlencoded";
 48         SetWebRequest(request);
 49         return ReadXmlResponse(request.GetResponse());
 50     }
 51 
 52 
 53     /**//// <summary>
 54     /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
 55     /// </summary>
 56     public static XmlDocument QuerySoapWebService(String URL , String MethodName , Hashtable Pars)
 57     {
 58         if (_xmlNamespaces.ContainsKey(URL))
 59         {
 60             return QuerySoapWebService(URL , MethodName , Pars , _xmlNamespaces[URL].ToString());
 61         }
 62         else
 63         {
 64             return QuerySoapWebService(URL , MethodName , Pars ,GetNamespace(URL));
 65         }
 66     }
 67 
 68     private static XmlDocument QuerySoapWebService(String URL , String MethodName , Hashtable Pars , string XmlNs)
 69     {    //By 同济黄正 http://hz932.ys168.com 2008-3-19
 70         _xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率
 71         HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
 72         request.Method = "POST";
 73         request.ContentType = "text/xml; charset=utf-8";
 74         request.Headers.Add("SOAPAction" , """ + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + """);
 75         SetWebRequest(request);
 76         byte[] data = EncodeParsToSoap(Pars , XmlNs , MethodName);
 77         WriteRequestData(request , data);
 78         XmlDocument doc = new XmlDocument() , doc2 = new XmlDocument();
 79         doc = ReadXmlResponse(request.GetResponse());
 80 
 81         XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
 82         mgr.AddNamespace("soap" , "http://schemas.xmlsoap.org/soap/envelope/");
 83         String RetXml = doc.SelectSingleNode("//soap:Body/*/*" , mgr).InnerXml;
 84         doc2.LoadXml("<root>" + RetXml + "</root>");
 85         AddDelaration(doc2);
 86         return doc2;
 87     }
 88     private static string GetNamespace(String URL)
 89     {
 90         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
 91         SetWebRequest(request);
 92         WebResponse response = request.GetResponse();
 93         StreamReader sr = new StreamReader(response.GetResponseStream() , Encoding.UTF8);
 94         XmlDocument doc = new XmlDocument();
 95         doc.LoadXml(sr.ReadToEnd());
 96         sr.Close();
 97         return doc.SelectSingleNode("//@targetNamespace").Value;
 98     }
 99     private static byte[] EncodeParsToSoap(Hashtable Pars , String XmlNs , String MethodName)
100     {
101         XmlDocument doc = new XmlDocument();
102         doc.LoadXml("<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/"></soap:Envelope>");
103         AddDelaration(doc);
104         XmlElement soapBody = doc.CreateElement("soap" , "Body" , "http://schemas.xmlsoap.org/soap/envelope/");
105         XmlElement soapMethod = doc.CreateElement(MethodName);
106         soapMethod.SetAttribute("xmlns" , XmlNs);
107         foreach (string k in Pars.Keys)
108         {
109             XmlElement soapPar = doc.CreateElement(k);
110             soapPar.InnerXml  = ObjectToSoapXml(Pars[k]);
111             soapMethod.AppendChild(soapPar);
112         }
113         soapBody.AppendChild(soapMethod);
114         doc.DocumentElement.AppendChild(soapBody);
115         return Encoding.UTF8.GetBytes(doc.OuterXml);
116     }
117     private static string ObjectToSoapXml(object o)
118     {
119         XmlSerializer mySerializer = new XmlSerializer(o.GetType());
120         MemoryStream ms=new MemoryStream();
121         mySerializer.Serialize(ms,o);
122         XmlDocument doc=new XmlDocument();
123         doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
124         if(doc.DocumentElement !=null)
125         {
126             return  doc.DocumentElement.InnerXml ;
127         }
128         else
129         {
130             return o.ToString();
131         }
132     }
133     private static void SetWebRequest(HttpWebRequest request)
134     {
135         request.Credentials = CredentialCache.DefaultCredentials;
136         request.Timeout = 10000;
137     }
138 
139     private static void WriteRequestData(HttpWebRequest request , byte[] data)
140     {
141         request.ContentLength = data.Length;
142         Stream writer = request.GetRequestStream();
143         writer.Write(data , 0 , data.Length);
144         writer.Close();
145     }
146 
147     private static byte[] EncodePars(Hashtable Pars)
148     {
149         return Encoding.UTF8.GetBytes(ParsToString(Pars));
150     }
151 
152     private static String ParsToString(Hashtable Pars)
153     {
154         StringBuilder sb = new StringBuilder();
155         foreach (string k in Pars.Keys)
156         {
157             if (sb.Length > 0)
158             {
159                 sb.Append("&");
160             }
161             sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
162         }
163         return sb.ToString();
164     }
165 
166     private static XmlDocument ReadXmlResponse(WebResponse response)
167     {
168         StreamReader sr = new StreamReader(response.GetResponseStream() , Encoding.UTF8);
169         String retXml = sr.ReadToEnd();
170         sr.Close();
171         XmlDocument doc = new XmlDocument();
172         doc.LoadXml(retXml);
173         return doc;
174     }
175 
176     private static void AddDelaration(XmlDocument doc)
177     {
178         XmlDeclaration decl = doc.CreateXmlDeclaration("1.0" , "utf-8" , null);
179         doc.InsertBefore(decl , doc.DocumentElement);
180     }
181 }
 1 public static string GetCustomerList()
 2         {
 3             string ServiceUrl = "";
 4             string InterfaceName = "regcustomerSearchInfo";
 5 
 6             Hashtable p = new Hashtable();
 7             p["account"] = "";
 8             p["password"] = "";
 9             p["conditions"] = new regcustomer_search_condition()
10             {
11                 regcustomer_gas_code = "12345678",
12                 regcustomer_name = "",
13                 regcustomer_gas_address = "",
14                 regcustomer_mobile = "",
15                 regcustomer_telephone = ""
16             };
17 
18             XmlDocument doc = WebSvcCaller.QuerySoapWebService(ServiceUrl, InterfaceName, p);
19             return doc.InnerText;
20 
21         }

 

WebClient 方式适合传递基本类型参数,soap方式适合传递复杂类型参数。
注:soap请求,参数如果为自定义类,请求方要创建自定义类实体。
原文地址:https://www.cnblogs.com/0-0snail/p/9504726.html