C#动态webservice调用接口
C#动态webservice调用接口
usingSystem; usingSystem.Collections; usingSystem.IO; usingSystem.Net; usingSystem.Text; usingSystem.Xml; usingSystem.Xml.Serialization; namespaceHishop.Plugins { ///<summary> ///利用WebRequest/WebResponse进行WebService调用的类 ///</summary> publicclassWebServiceCaller { #regionTip:使用说明 //webServices应该支持Get和Post调用,在web.config应该增加以下代码 //<webServices> //<protocols> //<addname="HttpGet"/> //<addname="HttpPost"/> //</protocols> //</webServices> //调用示例: //Hashtableht=newHashtable();//Hashtable为webservice所需要的参数集 //ht.Add("str","test"); //ht.Add("b","true"); //XmlDocumentxx=WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx","HelloWorld",ht); //MessageBox.Show(xx.OuterXml); #endregion ///<summary> ///需要WebService支持Post调用 ///</summary> publicstaticXmlDocumentQueryPostWebService(StringURL,StringMethodName,HashtablePars) { HttpWebRequestrequest=(HttpWebRequest)HttpWebRequest.Create(URL+"/"+MethodName); request.Method="POST"; request.ContentType="application/x-www-form-urlencoded"; SetWebRequest(request); byte[]data=EncodePars(Pars); WriteRequestData(request,data); returnReadXmlResponse(request.GetResponse()); } ///<summary> ///需要WebService支持Get调用 ///</summary> publicstaticXmlDocumentQueryGetWebService(StringURL,StringMethodName,HashtablePars) { HttpWebRequestrequest=(HttpWebRequest)HttpWebRequest.Create(URL+"/"+MethodName+"?"+ParsToString(Pars)); request.Method="GET"; request.ContentType="application/x-www-form-urlencoded"; SetWebRequest(request); returnReadXmlResponse(request.GetResponse()); } ///<summary> ///通用WebService调用(Soap),参数Pars为String类型的参数名、参数值 ///</summary> publicstaticXmlDocumentQuerySoapWebService(StringURL,StringMethodName,HashtablePars) { if(_xmlNamespaces.ContainsKey(URL)) { returnQuerySoapWebService(URL,MethodName,Pars,_xmlNamespaces[URL].ToString()); } else { returnQuerySoapWebService(URL,MethodName,Pars,GetNamespace(URL)); } } privatestaticXmlDocumentQuerySoapWebService(StringURL,StringMethodName,HashtablePars,stringXmlNs) { _xmlNamespaces[URL]=XmlNs;//加入缓存,提高效率 HttpWebRequestrequest=(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); XmlDocumentdoc=newXmlDocument(),doc2=newXmlDocument(); doc=ReadXmlResponse(request.GetResponse()); XmlNamespaceManagermgr=newXmlNamespaceManager(doc.NameTable); mgr.AddNamespace("soap","http://schemas.xmlsoap.org/soap/envelope/"); StringRetXml=doc.SelectSingleNode("//soap:Body/*/*",mgr).InnerXml; doc2.LoadXml("<root>"+RetXml+"</root>"); AddDelaration(doc2); returndoc2; } privatestaticstringGetNamespace(StringURL) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(URL+"?WSDL"); SetWebRequest(request); WebResponseresponse=request.GetResponse(); StreamReadersr=newStreamReader(response.GetResponseStream(),Encoding.UTF8); XmlDocumentdoc=newXmlDocument(); doc.LoadXml(sr.ReadToEnd()); sr.Close(); returndoc.SelectSingleNode("//@targetNamespace").Value; } privatestaticbyte[]EncodeParsToSoap(HashtablePars,StringXmlNs,StringMethodName) { XmlDocumentdoc=newXmlDocument(); doc.LoadXml("<soap:Envelopexmlns: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); //XmlElementsoapBody=doc.createElement_x_x("soap","Body","http://schemas.xmlsoap.org/soap/envelope/"); XmlElementsoapBody=doc.CreateElement("soap","Body","http://schemas.xmlsoap.org/soap/envelope/"); //XmlElementsoapMethod=doc.createElement_x_x(MethodName); XmlElementsoapMethod=doc.CreateElement(MethodName); soapMethod.SetAttribute("xmlns",XmlNs); foreach(stringkinPars.Keys) { //XmlElementsoapPar=doc.createElement_x_x(k); XmlElementsoapPar=doc.CreateElement(k); soapPar.InnerXml=ObjectToSoapXml(Pars[k]); soapMethod.AppendChild(soapPar); } soapBody.AppendChild(soapMethod); doc.DocumentElement.AppendChild(soapBody); returnEncoding.UTF8.GetBytes(doc.OuterXml); } privatestaticstringObjectToSoapXml(objecto) { XmlSerializermySerializer=newXmlSerializer(o.GetType()); MemoryStreamms=newMemoryStream(); mySerializer.Serialize(ms,o); XmlDocumentdoc=newXmlDocument(); doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray())); if(doc.DocumentElement!=null) { returndoc.DocumentElement.InnerXml; } else { returno.ToString(); } } ///<summary> ///设置凭证与超时时间 ///</summary> ///<paramname="request"></param> privatestaticvoidSetWebRequest(HttpWebRequestrequest) { request.Credentials=CredentialCache.DefaultCredentials; request.Timeout=10000; } privatestaticvoidWriteRequestData(HttpWebRequestrequest,byte[]data) { request.ContentLength=data.Length; Streamwriter=request.GetRequestStream(); writer.Write(data,0,data.Length); writer.Close(); } privatestaticbyte[]EncodePars(HashtablePars) { returnEncoding.UTF8.GetBytes(ParsToString(Pars)); } privatestaticStringParsToString(HashtablePars) { StringBuildersb=newStringBuilder(); foreach(stringkinPars.Keys) { if(sb.Length>0) { sb.Append("&"); } //sb.Append(HttpUtility.UrlEncode(k)+"="+HttpUtility.UrlEncode(Pars[k].ToString())); } returnsb.ToString(); } privatestaticXmlDocumentReadXmlResponse(WebResponseresponse) { StreamReadersr=newStreamReader(response.GetResponseStream(),Encoding.UTF8); StringretXml=sr.ReadToEnd(); sr.Close(); XmlDocumentdoc=newXmlDocument(); doc.LoadXml(retXml); returndoc; } privatestaticvoidAddDelaration(XmlDocumentdoc) { XmlDeclarationdecl=doc.CreateXmlDeclaration("1.0","utf-8",null); doc.InsertBefore(decl,doc.DocumentElement); } privatestaticHashtable_xmlNamespaces=newHashtable();//缓存xmlNamespace,避免重复调用GetNamespace } }
//调用并读取解析返回结果 DataSetds=newDataSet(); XmlNodexmlNode1; XmlDataDocumentxd=newXmlDataDocument(); StringBuildersb; Hashtableht=newHashtable(); ht.Add("xmlIn","<Request><MemCode>001</MemCode></Request>"); xmlNode1=Hishop.Plugins.WebServiceCaller.QuerySoapWebService("http://xxx.xxxx.com/Service.asmx","SinPointQuery",ht); if(xmlNode1==null) { return; } stringxmlstr=HttpUtility.HtmlDecode(xmlNode1.OuterXml); sb=newStringBuilder(xmlstr); if(sb.ToString().Equals("")) { return; } xd.LoadXml(sb.ToString()); ds.ReadXml(newXmlNodeReader(xd)); //ds可以返回出结果集
示例二:
1.动态调用的方法:
///<summary> ///动态webservice调用 ///</summary> ///<returns>string</returns> publicstringwsTest() { stringurl="http://localhost:8080/myWebserviceTest/services/myServices?wsdl";//wsdl地址 stringname="wsTest";//javaWebService开放的接口 WebServiceProxywsd=newWebServiceProxy(url,name); string[]str={"测试c#调用java的webService","HelloWebService"}; stringsuc=(string)wsd.ExecuteQuery(name,str); returnsuc; }
2.动态调用具体类:
usingSystem; usingSystem.Collections; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Linq; usingSystem.Web; usingSystem.Web.Services; usingSystem.Web.Services.Protocols; usingSystem.Xml.Linq; usingSystem.IO; usingSystem.Net; usingSystem.CodeDom; usingSystem.CodeDom.Compiler; usingSystem.Web.Services.Description; usingSystem.Xml.Serialization; usingSystem.Web.Services.Discovery; usingSystem.Xml.Schema; usingSystem.Text; usingSystem.Security.Cryptography; usingSystem.Reflection; usingSystem.Collections.Generic; usingSystem.Xml; namespaceTPSVService { ///<summary> ///WebServiceProxy的摘要说明 ///</summary> [WebService(Namespace="http://tempuri.org/")] [WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] //若要允许使用ASP.NETAJAX从脚本中调用此Web服务,请取消对下行的注释。 //[System.Web.Script.Services.ScriptService] publicclassWebServiceProxy:System.Web.Services.WebService { #region私有变量和属性定义 ///<summary> ///web服务地址 ///</summary> privatestring_wsdlUrl=string.Empty; ///<summary> ///web服务名称 ///</summary> privatestring_wsdlName=string.Empty; ///<summary> ///代理类命名空间 ///</summary> privatestring_wsdlNamespace="FrameWork.WebService.DynamicWebServiceCalling.{0}"; ///<summary> ///代理类类型名称 ///</summary> privateType_typeName=null; ///<summary> ///程序集名称 ///</summary> privatestring_assName=string.Empty; ///<summary> ///代理类所在程序集路径 ///</summary> privatestring_assPath=string.Empty; ///<summary> ///代理类的实例 ///</summary> privateobject_instance=null; ///<summary> ///代理类的实例 ///</summary> privateobjectInstance { get { if(_instance==null) { _instance=Activator.CreateInstance(_typeName); return_instance; } else return_instance; } } #endregion #region构造函数 publicWebServiceProxy(stringwsdlUrl) { this._wsdlUrl=wsdlUrl; stringwsdlName=WebServiceProxy.getWsclassName(wsdlUrl); this._wsdlName=wsdlName; this._assName=string.Format(_wsdlNamespace,wsdlName); this._assPath=Path.GetTempPath()+this._assName+getMd5Sum(this._wsdlUrl)+".dll"; this.CreateServiceAssembly(); } publicWebServiceProxy(stringwsdlUrl,stringwsdlName) { this._wsdlUrl=wsdlUrl; this._wsdlName=wsdlName; this._assName=string.Format(_wsdlNamespace,wsdlName); this._assPath=Path.GetTempPath()+this._assName+getMd5Sum(this._wsdlUrl)+".dll"; this.CreateServiceAssembly(); } #endregion #region得到WSDL信息,生成本地代理类并编译为DLL,构造函数调用,类生成时加载 ///<summary> ///得到WSDL信息,生成本地代理类并编译为DLL ///</summary> privatevoidCreateServiceAssembly() { if(this.checkCache()) { this.initTypeName(); return; } if(string.IsNullOrEmpty(this._wsdlUrl)) { return; } try { //使用WebClient下载WSDL信息 WebClientweb=newWebClient(); Streamstream=web.OpenRead(this._wsdlUrl); ServiceDescriptiondescription=ServiceDescription.Read(stream);//创建和格式化WSDL文档 ServiceDescriptionImporterimporter=newServiceDescriptionImporter();//创建客户端代理代理类 importer.ProtocolName="Soap"; importer.Style=ServiceDescriptionImportStyle.Client;//生成客户端代理 importer.CodeGenerationOptions=CodeGenerationOptions.GenerateProperties|CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description,null,null);//添加WSDL文档 //使用CodeDom编译客户端代理类 CodeNamespacenmspace=newCodeNamespace(_assName);//为代理类添加命名空间 CodeCompileUnitunit=newCodeCompileUnit(); unit.Namespaces.Add(nmspace); this.checkForImports(this._wsdlUrl,importer); ServiceDescriptionImportWarningswarning=importer.Import(nmspace,unit); CodeDomProviderprovider=CodeDomProvider.CreateProvider("CSharp"); CompilerParametersparameter=newCompilerParameters(); parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); parameter.GenerateExecutable=false; parameter.GenerateInMemory=false; parameter.IncludeDebugInformation=false; CompilerResultsresult=provider.CompileAssemblyFromDom(parameter,unit); provider.Dispose(); if(result.Errors.HasErrors) { stringerrors=string.Format(@"编译错误:{0}错误!",result.Errors.Count); foreach(CompilerErrorerrorinresult.Errors) { errors+=error.ErrorText; } thrownewException(errors); } this.copyTempAssembly(result.PathToAssembly); this.initTypeName(); } catch(Exceptione) { thrownewException(e.Message); } } #endregion #region执行Web服务方法 ///<summary> ///执行代理类指定方法,有返回值 ///</summary> ///<paramname="methodName">方法名称</param> ///<paramname="param">参数</param> ///<returns>object</returns> publicobjectExecuteQuery(stringmethodName,object[]param) { objectrtnObj=null; string[]args=newstring[2]; List<string>list=newList<string>(); List<string>list1=newList<string>(); List<string>list2=newList<string>(); object[]obj=newobject[3]; try { if(this._typeName==null) { //记录Web服务访问类名错误日志代码位置 thrownewTypeLoadException("Web服务访问类名【"+this._wsdlName+"】不正确,请检查!"); } //调用方法 MethodInfomi=this._typeName.GetMethod(methodName); if(mi==null) { //记录Web服务方法名错误日志代码位置 thrownewTypeLoadException("Web服务访问方法名【"+methodName+"】不正确,请检查!"); } try { if(param==null) rtnObj=mi.Invoke(Instance,null); else{ list.Add("Hello"); list.Add("WebService"); list.Add("!"); list1.Add("I"); list1.Add("am"); list1.Add("test"); list2.Add("do"); list2.Add("it"); list2.Add("now"); obj[0]=list; obj[1]=list1; obj[2]=list2; rtnObj=mi.Invoke(Instance,newobject[]{obj}); //rtnObj=mi.Invoke(Instance,newobject[]{param}); } } catch(TypeLoadExceptiontle) { //记录Web服务方法参数个数错误日志代码位置 thrownewTypeLoadException("Web服务访问方法【"+methodName+"】参数个数不正确,请检查!",newTypeLoadException(tle.StackTrace)); } } catch(Exceptionex) { thrownewException(ex.Message,newException(ex.StackTrace)); } returnrtnObj; } ///<summary> ///执行代理类指定方法,无返回值 ///</summary> ///<paramname="methodName">方法名称</param> ///<paramname="param">参数</param> publicvoidExecuteNoQuery(stringmethodName,object[]param) { try { if(this._typeName==null) { //记录Web服务访问类名错误日志代码位置 thrownewTypeLoadException("Web服务访问类名【"+this._wsdlName+"】不正确,请检查!"); } //调用方法 MethodInfomi=this._typeName.GetMethod(methodName); if(mi==null) { //记录Web服务方法名错误日志代码位置 thrownewTypeLoadException("Web服务访问方法名【"+methodName+"】不正确,请检查!"); } try { if(param==null) mi.Invoke(Instance,null); else mi.Invoke(Instance,param); } catch(TypeLoadExceptiontle) { //记录Web服务方法参数个数错误日志代码位置 thrownewTypeLoadException("Web服务访问方法【"+methodName+"】参数个数不正确,请检查!",newTypeLoadException(tle.StackTrace)); } } catch(Exceptionex) { thrownewException(ex.Message,newException(ex.StackTrace)); } } #endregion #region私有方法 ///<summary> ///得到代理类类型名称 ///</summary> privatevoidinitTypeName() { AssemblyserviceAsm=Assembly.LoadFrom(this._assPath); Type[]types=serviceAsm.GetTypes(); stringobjTypeName=""; foreach(Typetintypes) { if(t.BaseType==typeof(SoapHttpClientProtocol)) { objTypeName=t.Name; break; } } _typeName=serviceAsm.GetType(this._assName+"."+objTypeName); } ///<summary> ///根据webservice文档架构向代理类添加ServiceDescription和XmlSchema ///</summary> ///<paramname="baseWSDLUrl">web服务地址</param> ///<paramname="importer">代理类</param> privatevoidcheckForImports(stringbaseWsdlUrl,ServiceDescriptionImporterimporter) { DiscoveryClientProtocoldcp=newDiscoveryClientProtocol(); dcp.DiscoverAny(baseWsdlUrl); dcp.ResolveAll(); foreach(objectosdindcp.Documents.Values) { if(osdisServiceDescription)importer.AddServiceDescription((ServiceDescription)osd,null,null);; if(osdisXmlSchema)importer.Schemas.Add((XmlSchema)osd); } } ///<summary> ///复制程序集到指定路径 ///</summary> ///<paramname="pathToAssembly">程序集路径</param> privatevoidcopyTempAssembly(stringpathToAssembly) { File.Copy(pathToAssembly,this._assPath); } privatestringgetMd5Sum(stringstr) { Encoderenc=System.Text.Encoding.Unicode.GetEncoder(); byte[]unicodeText=newbyte[str.Length*2]; enc.GetBytes(str.ToCharArray(),0,str.Length,unicodeText,0,true); MD5md5=newMD5CryptoServiceProvider(); byte[]result=md5.ComputeHash(unicodeText); StringBuildersb=newStringBuilder(); for(inti=0;i<result.Length;i++) { sb.Append(result[i].ToString("X2")); } returnsb.ToString(); } ///<summary> ///是否已经存在该程序集 ///</summary> ///<returns>false:不存在该程序集,true:已经存在该程序集</returns> privateboolcheckCache() { if(File.Exists(this._assPath)) { returntrue; } returnfalse; } //私有方法,默认取url入口的文件名为类名 privatestaticstringgetWsclassName(stringwsdlUrl) { string[]parts=wsdlUrl.Split('/'); string[]pps=parts[parts.Length-1].Split('.'); returnpps[0]; } #endregion } }
以上所述就是本文的全部内容了,希望大家能够喜欢。