C # dynamic WebService call interface

Source: Internet
Author: User
Tags foreach constructor soap md5 split urlencode xmlns wsdl

Dynamic call WebService, you can not add a Web reference, the line is just need to change the WSDL address on it

C # dynamic WebService call interface

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148-149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179-18 0 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 Using System; Using System.Collections; Using System.IO; Using System.Net; Using System.Text; Using System.Xml; Using System.Xml.Serialization; namespace Hishop.plugins {///<summary>///class webrequest/webresponse </summary> public using WebService for///invocation Class Webservicecaller {#region Tip: Use instructions//webservices should support get and post calls, Web.config should add the following code//<webservices>// <protocols>//<add name= "HttpGet"/>//<add name= "HttpPost"/>//</protocols>//</ Webservices>  //Call Example://hashtable HT = new Hashtable (); Hashtable is the set of parameters required for WebService//ht. ADD ("str", "Test"); Ht. ADD ("B", "true"); XmlDocument xx = Websvccaller.querysoapwebservice ("Http://localhost:81/service.asmx", "HelloWorld", HT); MessageBox.Show (xx. OuterXml); #endregion  ///<summary>///need WebService support post invocation///</summary> public static XmlDocument Querypostwe Bservice (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>///need webservice support get invocation///</summary> public static XmlDocument Querygetwebservice (St Ring 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>///Universal WebService Call (SOAP), parameter pars to string type parameter name, parameter value///</summary> public static XmlDocument Querysoapwebservice (String URL, String methodname, Hashtable Pars) {if (_xmlnamespaces.containskey (URL)) {R Eturn Querysoapwebservice (URL, MethodName, Pars, _xmlnamespaces[url). ToString ()); else {return Querysoapwebservice (URL, methodname, Pars, GetNamespace (URL));}   private static XmlDocument Querysoapwebservice (String URL, String methodname, Hashtable Pars, String XmlNs) {_xmln Amespaces[url] = xmlns;//Add cache, improve efficiency 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; } 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; }   private static byte[] Encodeparstosoap (Hashtable Pars, String XmlNs, String methodname) {XmlDocument doc = new X Mldocument (); 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); private static string Objecttosoapxml (object o) {XmlSerializer myserializer = new XmlSerializer (O.gettype ()); MemoryStream ms = new MemoryStream (); Myserializer.serialize (MS, O); XmlDocument doc = new XmlDocument (); Doc. Loadxml (Encoding.UTF8.GetString) (Ms. ToArray ())); if (Doc. DocumentElement!= null) {return doc. Documentelement.innerxml; else {return o.tostring ();}}  ///<summary>///set voucher and timeout///</summary>///<param name= "Request" ></param> private Static void Setwebrequest (HttpWebRequest request) {request. Credentials = CredentialCache.DefaultCredentials; Request. Timeout = 10000; }   private static void Writerequestdata (HttpWebRequest request, byte[] data) {request. ContentLength = data. Length; Stream writer = Request. GetRequestStream (); Writer. Write (data, 0, data. Length); Writer. Close (); }   private static byte[] Encodepars (Hashtable Pars) {return Encoding.UTF8.GetBytes (parstostring (Pars));}   PR Ivate 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 (); }   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; }   private static void Adddelaration (XmlDocument doc) {XmlDeclaration decl = doc. Createxmldeclaration ("1.0", "Utf-8", null); Doc. InsertBefore (Decl, Doc. DocumentElement); }   private static Hashtable _xmlnamespaces = new Hashtable ()//cache xmlnamespace to avoid repeated calls to GetNamespace}}

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21-22 Call and read the parse return result DataSet ds = new DataSet (); XmlNode XmlNode1; XmlDataDocument xd = new XmlDataDocument (); StringBuilder SB; Hashtable ht = new Hashtable (); 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;} string xmlstr= Httputility.htmldecode (xmlnode1.outerxml); SB = new StringBuilder (XMLSTR); if (sb.) ToString (). Equals ("")) {return;} Xd. Loadxml (sb.) ToString ()); Ds. READXML (New XmlNodeReader (XD)); DS can return a result set

Example two:

1. Method of dynamic invocation:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16 <summary>///Dynamic WebService call///</summary>///<returns>string</returns> public string Wstest () {String url = "HTTP://LOCALHOST:8080/MYWEBSERVICETEST/SERVICES/MYSERVICES?WSDL";//wsdl address string name = "   Wstest ";//javawebservice Open Interface WebServiceProxy WSD = new WebServiceProxy (URL, name);   string[] str = {"Test C # Invoke Java WebService", "Hello WebService"}; String suc = (string) WSD.   ExecuteQuery (name, str); return suc; }

2. Dynamic invocation of specific classes:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30-31 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 The 96 97 98 99 100 101 102 103 104 105 106 107 108 109 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140-1 41 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170-171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201-2 02 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231-232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262-2 63 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298-299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329-3 30 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359-360 361 362 Using System; Using System.Collections; Using System.ComponentModel; Using System.Data; Using System.Linq; Using System.Web; Using System.Web.Services; Using System.Web.Services.Protocols; Using System.Xml.Linq; &nbsp; &nbsp; using System.IO; Using System.Net; Using System.CodeDom; Using System.CodeDom.Compiler; Using System.Web.Services.Description; Using System.Xml.Serialization; Using System.Web.Services.Discovery; Using System.Xml.Schema; Using System.Text; Using System.Security.Cryptography; Using System.Reflection; Using System.Collections.Generic; Using System.Xml; &nbsp; namespace Tpsvservice {///&lt;summary&gt;///webserviceproxy Summary description///&lt;/summary&gt; [WebService (Namespace = "http://tempuri.org/")] [webservicebinding (ConformsTo = wsiprofiles.basicprofile1_1)] [ToolboxItem (false)]//To allow use of the asp.net AJAX calls this Web service from a script, uncomment the line. [System.Web.Script.Services.ScriptService] public class WebServiceProxy:System.Web.Services.WebService {&nbsp; # Region private variables and attribute definitions///;summary&gt;///Web service address///&lt;/summary&gt; private String _wsdlurl = String. Empty; &lt;summary&gt;///Web service name///&lt;/summary&gt; private String _wsdlname = String. Empty; &lt;summary&gt;///proxy class namespace///&lt;/summary&gt; private string _wsdlnamespace = " FrameWork.WebService.DynamicWebServiceCalling. {0} "; &lt;summary&gt;///proxy class type name///&lt;/summary&gt; private type _typename = null; &lt;summary&gt;///assembly name///&lt;/summary&gt; private String _assname = String. Empty; &lt;summary&gt;///proxy class is in the assembly path///&lt;/summary&gt; private String _asspath = String. Empty; &lt;summary&gt;///proxy class instance///&lt;/summary&gt; Private object _instance = null; &lt;summary&gt;///instance of proxy class///&lt;/summary&gt; private object Instance {get {if (_instance = = null) {_instance = A Ctivator. CreateInstance (_typename); return _instance; else return _instance; #endregion &nbsp; #region Constructor public WebServiceProxy (string wsdlurl) {&nbsp; This._wsdlurl = wsdlurl; string Wsdlnam E = Webserviceproxy.getwsclassname (Wsdlurl); This._wsdlname = Wsdlname; This._assname = string. Format (_wsdlnamespace, wsdlname); This._asspath = Path.gettemppath () + This._assname + getmd5sum (this._wsdlurl) + ". dll"; This. Createserviceassembly (); } &nbsp; Public WebServiceProxy (String wsdlurl, String wsdlname) {this._wsdlurl = wsdlurl; this._wsdlname = wsdlname; thi S._assname = string. Format (_wsdlnamespace, wsdlname); This._asspath = Path.gettemppath () + This._assname + getmd5sum (this._wsdlurl) + ". dll"; This. Createserviceassembly (); #endregion &nbsp; #region Get WSDL information, generate local proxy class and compile as DLL, constructor call, load///&lt;summary&gt;///When class builds, generate WSDL information, build local proxy class and compile as DLL///& lt;/summary&gt; private void createserviceassembly () {if (This.checkcache ()) {this.inittypename (); return;} if (String. IsNullOrEmpty (This._wsdlurl)) {return;} try {//Use WebClient to download wsdl information WebClient web = new WebClient (); Stream stream = web. OpenRead (This._wsdlurl); ServiceDescription Description = Servicedescription.read (stream);//Create and formatWSDL Document ServiceDescriptionImporter Importer = new ServiceDescriptionImporter ();//Create Client proxy class importer. ProtocolName = "Soap"; Importer. Style = servicedescriptionimportstyle.client; Generate Client Agent importer. CodeGenerationOptions = Codegenerationoptions.generateproperties | Codegenerationoptions.generatenewasync; Importer. Addservicedescription (description, NULL, NULL);//Add WSDL Document//use CodeDom to compile client proxy class CodeNamespace Nmspace = new CodeNamespace (_assname); Add a namespace to the proxy class CodeCompileUnit unit = new CodeCompileUnit (); Unit. Namespaces.add (Nmspace); This.checkforimports (This._wsdlurl, importer); Servicedescriptionimportwarnings warning = importer. Import (nmspace, unit); CodeDomProvider Provider = Codedomprovider.createprovider ("CSharp"); CompilerParameters parameter = new CompilerParameters (); 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; CompilerResults result = provider.compileassemblyfromdom (parameter, unit); Provider. Dispose (); if (result. errors.haserrors) {string Errors = string. Format (@) Compilation error: {0} Error! ", result. Errors.Count); foreach (compilererror error in result.) Errors) {Errors = = error. ErrorText; } throw new Exception (errors); } this.copytempassembly (Result. pathtoassembly); This.inittypename (); catch (Exception e) {throw new Exception (E.message);}} #endregion &nbsp; #region Execute Web service methods///&lt;summary&gt;///Execute proxy class Specify method with return value///&lt;/summary&gt;///&lt;param name= "Methods Name &gt; method name &lt;/param&gt;///&lt;param name= "param" &gt; Parameter &lt;/param&gt;///&lt;returns&gt;object&lt;/returns &gt; Public Object ExecuteQuery (String methodname, object[] param) {object rtnobj = null; string[] args = new string[2]; list&lt;string&gt; list = new list&lt;string&gt; (); List&lt;string&gt; List1 = new List&lt;strIng&gt; (); list&lt;string&gt; list2 = new list&lt;string&gt; (); object[] obj = new Object[3]; &nbsp; try {if (This._typename = null) {//Log Web Service access class name error log code location throw new TypeLoadException ("Web Service Access Class name" + This._wsdlname + "" Not correct, please check! "); } Call method MethodInfo mi = This._typename.getmethod (methodname); if (mi = = null) {//Log Web service method name error log code location throw new TypeLoadException ("Web Service access Method name" + methodname + "" is not correct, please check!) "); } try {if (param = null) rtnobj = mi. Invoke (Instance, NULL); else {list. ADD ("Hello"); List. ADD ("WebService"); List. ADD ("!"); &nbsp; List1. ADD ("I"); List1. ADD ("AM"); List1. ADD ("test"); &nbsp; List2. ADD ("Do"); List2. ADD ("it"); List2. ADD ("Now"); &nbsp; Obj[0] = list; OBJ[1] = List1; OBJ[2] = List2; &nbsp; Rtnobj = mi. Invoke (Instance, new object[] {obj}); Rtnobj = mi. Invoke (Instance, new object[] {param}); } catch (TypeLoadException tle) {//Log Web service method parameters error log code location throw new TypeLoadException ("Web Service access Method" + methodname + "") Number of parameters Not correct, please check! , New TypeLoadException (TLE). StackTrace)); } catch (Exception ex) {throw new Exception (ex. Message, New Exception (ex. StackTrace)); return rtnobj; } &nbsp;///&lt;summary&gt;///Execution proxy class specifies method, no return value///&lt;/summary&gt;///&lt;param name= "methodname" &gt; method name &lt;/param& Gt &lt;param name= "param" &gt; Parameters &lt;/param&gt; public void Executenoquery (String methodname, object[] param) {try {if T His._typename = = null) {//Log Web Service access class name error log code location throw new TypeLoadException ("Web Service Access Class name" + This._wsdlname + "" Not correct, please check!) "); } Call method MethodInfo mi = This._typename.getmethod (methodname); if (mi = = null) {//Log Web service method name error log code location throw new TypeLoadException ("Web Service access Method name" + methodname + "" is not correct, please check!) "); } try {if (param = null) mi. Invoke (Instance, NULL); Else mi. Invoke (Instance, param); catch (TypeLoadException tle) {//Log Web service method parameters error log code location throw new TypeLoadException (Web Service access Method "+ methodname +" "parameter number is not positive Indeed, please check! , New TypeLoadException (TLE). StackTrace)); } catch (Exception ex) {throw new Exception (ex. Message, New Exception (ex. StackTrace)); }#endregion &nbsp; #region Private method///&lt;summary&gt;///Gets the proxy class type name///&lt;/summary&gt; private void Inittypename () {Asse mbly serviceasm = Assembly.LoadFrom (This._asspath); type[] types = Serviceasm.gettypes (); String objtypename = ""; foreach (Type t in types) {if (T.basetype = = typeof (SoapHttpClientProtocol)) {objtypename = T.name; break;}} _typename = Serviceasm.gettype (This._assname + "." + Objtypename); } &nbsp;///&lt;summary&gt;///add servicedescription and XmlSchema///&lt;/summary&gt;///&lt;param N to the proxy class according to the Web Service document schema Ame= "Basewsdlurl" &gt;web service address &lt;/param&gt;///&lt;param name= "Importer" &gt; proxy class &lt;/param&gt; private void Checkforimports (String basewsdlurl, ServiceDescriptionImporter Importer) {Discoveryclientprotocol DCP = new Discoveryclientprotocol (); Dcp. Discoverany (Basewsdlurl); Dcp. ResolveAll (); foreach (Object OSD in DCP). Documents.values) {if (OSD is servicedescription) importer. Addservicedescription ((servicedescription) OSD, NULL, NULL);; If (OSD is XmlSchema)Importer. Schemas.add ((XmlSchema) OSD); } &nbsp;///&lt;summary&gt;///replication assembly to the specified path///&lt;/summary&gt;///&lt;param name= "pathtoassembly" &gt; Assembly path &lt;/param &gt; private void copytempassembly (string pathtoassembly) {file.copy (pathtoassembly, This._asspath);} &nbsp; Private St Ring Getmd5sum (String str) {Encoder enc = System.Text.Encoding.Unicode.GetEncoder (); byte[] UnicodeText = new Byte[str. Length * 2]; Enc. GetBytes (str. ToCharArray (), 0, str. Length, UnicodeText, 0, true); MD5 MD5 = new MD5CryptoServiceProvider (); Byte[] result = Md5.computehash (UnicodeText); StringBuilder sb = new StringBuilder (); for (int i = 0; I &lt; result. Length; i++) {sb. Append (Result[i]. ToString ("X2")); Return SB. ToString (); &nbsp;///&lt;summary&gt;///whether the assembly///&lt;/summary&gt;///&lt;returns&gt;false: This assembly is not present, true: The assembly already exists &lt;/ returns&gt; private bool Checkcache () {if (file.exists (This._asspath)) {return true;} return false;} &nbsp;//private method, default fetch The file name for the URL entry is the class name private static string GetwsclassName (String wsdlurl) {string[] parts = wsdlurl.split ('/'); string[] pps = parts[parts. LENGTH-1]. Split ('. '); return pps[0]; } #endregion}}

The above is the entire contents of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.