标签:
WebService调用方法总结
一、客户端代理类
1、方式一。
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web.Services.Description; using System.Xml; using System.Xml.Serialization; namespace NetWebServiceInvoke { /// <summary> /// 通过生成代理类调用WebService /// </summary> public class InvokeByProxy1 { private object agent; private Type agentType; private const string CODE_NAMESPACE = "NetWebServiceInvoke.WebServiceAgent.Dynamic"; /// <summary> /// 构造函数 /// </summary> /// <param name="url">统一资源定位符</param> public InvokeByProxy1(string url) { XmlTextReader reader = new XmlTextReader(url + "?wsdl"); //创建和格式化 WSDL 文档 ServiceDescription sd = ServiceDescription.Read(reader); //创建客户端代理代理类 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, null, null); //使用 CodeDom 编译客户端代理类 CodeNamespace cn = new CodeNamespace(CODE_NAMESPACE); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = icc.CompileAssemblyFromDom(cp, ccu); agentType = cr.CompiledAssembly.GetTypes()[0]; agent = Activator.CreateInstance(agentType); } ///<summary> ///调用指定的方法 ///</summary> ///<param name="methodName">方法名,大小写敏感</param> ///<param name="args">参数,按照参数顺序赋值</param> ///<returns>Web服务的返回值</returns> public object Invoke(string methodName, params object[] args) { MethodInfo mi = agentType.GetMethod(methodName); return this.Invoke(mi, args); } ///<summary> ///调用指定方法 ///</summary> ///<param name="method">方法信息</param> ///<param name="args">参数,按照参数顺序赋值</param> ///<returns>Web服务的返回值</returns> public object Invoke(MethodInfo method, params object[] args) { return method.Invoke(agent, args); } /// <summary> /// 获得代理所有方法 /// </summary> public MethodInfo[] Methods { get { return agentType.GetMethods(); } } } }
2、方式二。
1 using Microsoft.CSharp; 2 using System; 3 using System.CodeDom; 4 using System.CodeDom.Compiler; 5 using System.Collections.Generic; 6 using System.IO; 7 using System.Linq; 8 using System.Net; 9 using System.Reflection; 10 using System.Text; 11 using System.Threading.Tasks; 12 using System.Web.Services.Description; 13 using System.Xml; 14 using System.Xml.Serialization; 15 16 namespace NetWebServiceInvoke 17 { 18 /// <summary> 19 /// 通过生成代理类调用WebService 20 /// </summary> 21 public class InvokeByProxy2 22 { 23 /// <summary> 24 /// 动态调用web服务 25 /// </summary> 26 /// <param name="url">统一资源定位符</param> 27 /// <param name="methodname">方法名</param> 28 /// <param name="args">参数</param> 29 /// <returns></returns> 30 public static object InvokeWebService(string url, string methodname, object[] args) 31 { 32 return InvokeByProxy2.InvokeWebService(url, null, methodname, args); 33 } 34 35 /// <summary> 36 /// 动态调用web服务 37 /// </summary> 38 /// <param name="url">统一资源定位雷符</param> 39 /// <param name="classname">类名</param> 40 /// <param name="methodname">方法名</param> 41 /// <param name="args">参数</param> 42 /// <returns></returns> 43 public static object InvokeWebService(string url, string classname, string methodname, object[] args) 44 { 45 string @namespace = "NetWebServiceInvoke.WebService.DynamicWebCalling"; 46 if ((classname == null) || (classname == "")) 47 { 48 classname = InvokeByProxy2.GetWsClassName(url); 49 } 50 51 try 52 { 53 //获取WSDL 54 WebClient wc = new WebClient(); 55 Stream stream = wc.OpenRead(url + "?WSDL"); 56 ServiceDescription sd = ServiceDescription.Read(stream); 57 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); 58 sdi.AddServiceDescription(sd, "", ""); 59 CodeNamespace cn = new CodeNamespace(@namespace); 60 61 //生成客户端代理类代码 62 CodeCompileUnit ccu = new CodeCompileUnit(); 63 ccu.Namespaces.Add(cn); 64 sdi.Import(cn, ccu); 65 CSharpCodeProvider csc = new CSharpCodeProvider(); 66 67 //设定编译参数 68 CompilerParameters cplist = new CompilerParameters(); 69 cplist.GenerateExecutable = false; 70 cplist.GenerateInMemory = true; 71 cplist.ReferencedAssemblies.Add("System.dll"); 72 cplist.ReferencedAssemblies.Add("System.XML.dll"); 73 cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); 74 cplist.ReferencedAssemblies.Add("System.Data.dll"); 75 76 //编译代理类 77 CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu); 78 if (true == cr.Errors.HasErrors) 79 { 80 System.Text.StringBuilder sb = new System.Text.StringBuilder(); 81 foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) 82 { 83 sb.Append(ce.ToString()); 84 sb.Append(System.Environment.NewLine); 85 } 86 throw new Exception(sb.ToString()); 87 } 88 89 //生成代理实例,并调用方法 90 System.Reflection.Assembly assembly = cr.CompiledAssembly; 91 Type t = assembly.GetType(@namespace + "." + classname, true, true); 92 object obj = Activator.CreateInstance(t); 93 System.Reflection.MethodInfo mi = t.GetMethod(methodname); 94 95 return mi.Invoke(obj, args); 96 } 97 catch (Exception ex) 98 { 99 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); 100 } 101 } 102 103 /// <summary> 104 /// 获取类名 105 /// </summary> 106 /// <param name="wsUrl">统一资源定位雷符</param> 107 /// <returns></returns> 108 private static string GetWsClassName(string wsUrl) 109 { 110 string[] parts = wsUrl.Split(‘/‘); 111 string[] pps = parts[parts.Length - 1].Split(‘.‘); 112 113 return pps[0]; 114 } 115 116 } 117 }
3、方式三。
项目中直接添加服务引用。
二、HttpWebRequest
Get、Post请求方式。SOAP协议。
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace NetWebServiceInvoke { /// <summary> /// 通过HttpWebRequest调用WebService /// </summary> public class InvokeByHttpWebRequest { #region 定义 /// <summary> /// 缓存xmlNamespace,避免重复调用GetNamespace /// </summary> private static Hashtable _xmlNamespaces = new Hashtable(); #endregion #region 调用方式 /// <summary> /// Post方式 /// </summary> /// <param name="URL">统一资源定位符</param> /// <param name="MethodName">方法名</param> /// <param name="Pars">参数</param> /// <returns>xml文档</returns> public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; SetWebRequest(request); byte[] data = EncodePars(Pars); WriteRequestData(request, data); return ReadXmlResponse(request.GetResponse()); } /// <summary> /// Get方式 /// </summary> /// <param name="URL">统一资源定位符</param> /// <param name="MethodName">方法名</param> /// <param name="Pars">参数</param> /// <returns>xml文档</returns> public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars)); request.Method = "GET"; request.ContentType = "application/x-www-form-urlencoded"; SetWebRequest(request); return ReadXmlResponse(request.GetResponse()); } /// <summary> /// Soap方式 /// </summary> /// <param name="URL">统一资源定位符</param> /// <param name="MethodName">方法名</param> /// <param name="Pars">参数</param> /// <returns>xml文档</returns> public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars) { if (_xmlNamespaces.ContainsKey(URL)) { return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString()); } else { return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL)); } } /// <summary> /// Soap方式 /// </summary> /// <param name="URL">统一资源定位符</param> /// <param name="MethodName">方法名</param> /// <param name="Pars">参数</param> /// <param name="XmlNs">xml命名空间</param> /// <returns>xml文档</returns> private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs) { _xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL); request.Method = "POST"; request.ContentType = "text/xml; charset=utf-8"; request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\""); SetWebRequest(request); byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName); WriteRequestData(request, data); XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument(); doc = ReadXmlResponse(request.GetResponse()); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml; doc2.LoadXml("<root>" + RetXml + "</root>"); AddDelaration(doc2); return doc2; } #endregion #region 设置 /// <summary> /// 获得命名空间 /// </summary> /// <param name="URL">统一资源定位符</param> /// <returns></returns> private static string GetNamespace(String URL) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL"); SetWebRequest(request); WebResponse response = request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); XmlDocument doc = new XmlDocument(); doc.LoadXml(sr.ReadToEnd()); sr.Close(); return doc.SelectSingleNode("//@targetNamespace").Value; } /// <summary> /// 设置凭证与超时时间 /// </summary> /// <param name="request">请求</param> private static void SetWebRequest(HttpWebRequest request) { request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; } /// <summary> /// 写入请求数据 /// </summary> /// <param name="request">请求</param> /// <param name="data">数据</param> private static void WriteRequestData(HttpWebRequest request, byte[] data) { request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); } #endregion #region 参数 /// <summary> /// 参数编码 /// </summary> /// <param name="Pars">参数</param> /// <returns>字节数组</returns> private static byte[] EncodePars(Hashtable Pars) { return Encoding.UTF8.GetBytes(ParsToString(Pars)); } /// <summary> /// 参数编码 /// </summary> /// <param name="Pars">参数</param> /// <returns></returns> private static String ParsToString(Hashtable Pars) { StringBuilder sb = new StringBuilder(); foreach (string k in Pars.Keys) { if (sb.Length > 0) { sb.Append("&"); } //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString())); } return sb.ToString(); } /// <summary> /// Soap参数编码 /// </summary> /// <param name="Pars">参数</param> /// <param name="XmlNs">xml命名空间</param> /// <param name="MethodName">方法</param> /// <returns>字节数组</returns> private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName) { XmlDocument doc = new XmlDocument(); 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>"); AddDelaration(doc); //XmlElement soapBody = doc.createElement_x_x("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/"); XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/"); //XmlElement soapMethod = doc.createElement_x_x(MethodName); XmlElement soapMethod = doc.CreateElement(MethodName); soapMethod.SetAttribute("xmlns", XmlNs); foreach (string k in Pars.Keys) { //XmlElement soapPar = doc.createElement_x_x(k); XmlElement soapPar = doc.CreateElement(k); soapPar.InnerXml = ObjectToSoapXml(Pars[k]); soapMethod.AppendChild(soapPar); } soapBody.AppendChild(soapMethod); doc.DocumentElement.AppendChild(soapBody); return Encoding.UTF8.GetBytes(doc.OuterXml); } /// <summary> /// obj序列化xml /// </summary> /// <param name="obj"></param> /// <returns>结果</returns> private static string ObjectToSoapXml(object obj) { XmlSerializer mySerializer = new XmlSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); mySerializer.Serialize(ms, obj); XmlDocument doc = new XmlDocument(); doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray())); if (doc.DocumentElement != null) { return doc.DocumentElement.InnerXml; } else { return obj.ToString(); } } #endregion #region 响应数据 /// <summary> /// 响应数据读取 /// </summary> /// <param name="response">响应</param> /// <returns>xml文档</returns> private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } /// <summary> /// xml文档添加声明 /// </summary> /// <param name="doc">xml文档</param> private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } #endregion } }
通过此方法返回的都是xml格式的数据,如返回json格式该如何。
Demo下载地址:http://pan.baidu.com/s/1eQntsUe
本文摘自:
http://blog.csdn.net/ysq5202121/article/details/6942813
http://www.cnblogs.com/eagle1986/archive/2012/09/03/2669699.html
标签:
原文地址:http://www.cnblogs.com/zhang-lei/p/4975620.html