动态webservice调用接口并读取解析返回结果
这里给大家带来的是动态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可以返回出结果集
以上所述就是本文的全部内容了,希望大家能够喜欢。