HTTP request post and get call interface and reflection dynamic call WebServices class

Source: Internet
Author: User
Tags wsdl

This code is the API, websrvices dynamic invocation of the class, make the interface call is very useful.

WebServices Dynamic invocation of the use of reflection is a big drawback is inefficient, if there is a better dynamic call webservices method, I hope you do not hesitate to paste the code.

Using system;using system.io;using system.net;using system.text;using system.web;using System.Collections.Generic; Using system.codedom.compiler;using system.web.services.description;using system.codedom;using Microsoft.CSharp;/* Description: Provides HTTP, post, and get, webservices Dynamic Access remote interface * *******************/namespace demo{public static Class Httphelper {///////private static readonly string Defaultuserag for an auxiliary class for HTTP requests/// ent = "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; NET CLR 1.1.4322;. NET CLR 2.0.50727) ";//browser private static Encoding requestencoding = System.Text.Encoding. utf8;//Character Set #region Create a Get method HTTP request/////////////////////interface URL///interface URL ///The information returned by the interface///public static bool HttpGet (string URL, Dictionary dctparam, out string httpwebres ponsestring) {if (string. IsNullOrEmpty (URL)) {throw new ArgumentNullexception ("url");             } httpwebresponsestring = "";            HttpWebRequest request = null;  Stream stream = null;//is used to pass arguments to the stream httpwebresponse HttpWebResponse = null;                try {int i = 0;                StringBuilder buffer = new StringBuilder (); if (! (                        Dctparam = = null)) {foreach (string key in Dctparam.keys) { if (i > 0) {buffer.                        AppendFormat ("&{0}={1}", Key, (Dctparam[key])); } else {buffer.                        AppendFormat ("{0}={1}", Key, (Dctparam[key]));                    } i++; url = url + "?" + buffer.                ToString ();                } request = WebRequest.Create (URL) as HttpWebRequest; Request. Method= "GET";//Transmit request. ContentType = "application/x-www-form-urlencoded";//Protocol request. UserAgent = defaultuseragent;//requested client browser information, default IE request. Timeout = 6000;//timeout time, write dead 6 seconds request.                KeepAlive = false; DefaultConnectionLimit is the default of 2, and the current HTTP connection run out, causing subsequent getresponse or getrequeststream timeouts to die System.Net.Servi                Cepointmanager.defaultconnectionlimit = 50; Request.                Servicepoint.expect100continue = false; HttpWebResponse = Request.                GetResponse () as HttpWebResponse;                httpwebresponsestring = Readhttpwebresponse (HttpWebResponse);            return true; } catch (Exception ee) {httpwebresponsestring = ee.                ToString ();            return false; finally {if (stream! = null) {stream.                Close ();  } if (Request! = NULL)              { 
Request. Abort (); request = NULL; } if (HttpWebResponse! = null) {httpwebresponse.close (); HttpWebResponse = null; }}} #endregion #region create a post-mode HTTP request////////Create a post-way HTTP request Interface URL///parameter of interface URL///The message returned by the interface///public static bool HttpPost (string URL, Di Ctionary Dctparam, out string httpwebresponsestring) {if (string. IsNullOrEmpty (URL)) {throw new ArgumentNullException ("url"); } httpwebresponsestring = ""; HttpWebRequest request = null; Stream stream = null;//is used to pass arguments to the stream try {url = encodepostdata (URL); Request = WebRequest.Create (URL) as HttpWebRequest; Request. method = "POST";//Transmit request.ContentType = "application/x-www-form-urlencoded";//Protocol request. UserAgent = defaultuseragent;//requested client browser information, default IE request. Timeout = 6000;//timeout time, write dead 6 seconds//defaultconnectionlimit is the default of 2, and the current HTTP connection run out, resulting in subsequent getresponse or getrequest Stream timed out dead System.Net.ServicePointManager.DefaultConnectionLimit = 50; Request. Servicepoint.expect100continue = false; If the demand post data, converted to UTF-8 encoding byte[] data = Paramdataconvert (Dctparam); if (! ( data = null) {string s = requestencoding.getstring (data); stream = Request. GetRequestStream (); Stream. Write (Data, 0, data.length); } HttpWebResponse HttpWebResponse = Request. GetResponse () as HttpWebResponse; httpwebresponsestring = Readhttpwebresponse (HttpWebResponse); return true; } catch (ExceptionEE) {httpwebresponsestring = ee. ToString (); return false; finally {if (stream! = null) {stream. Close (); }}} #endregion #region reflection dynamic Call WebServices//////////Reflection Dynamic call WebServices// WebServices address, to? End of WSDL///method called///public static object Invokewebservice (string url, String meth Odname, object[] args) {string @namespace = "Demo";//The namespace of this page try { Gets the wsdl WebClient WC = new WebClient (); Stream stream = WC. OpenRead (URL); ServiceDescription sd = Servicedescription.read (stream); ServiceDescriptionImporter SDI = new ServiceDescriptionImporter (); Sdi. Addservicedescription (SD, "", ""); CodeNamespace cn = New CodeNamespace (@namespace); Generate the client proxy class code CodeCompileUnit CCU = new CodeCompileUnit (); Ccu. Namespaces.add (CN); Sdi. Import (CN, CCU); CSharpCodeProvider csc = new CSharpCodeProvider (); CSharpCodeProvider ICC = new CSharpCodeProvider (); Set compilation parameters CompilerParameters Cplist = new CompilerParameters (); Cplist. GenerateExecutable = false; Cplist. GenerateInMemory = true; Cplist. Referencedassemblies.add ("System.dll"); Cplist. Referencedassemblies.add ("System.XML.dll"); Cplist. Referencedassemblies.add ("System.Web.Services.dll"); Cplist. Referencedassemblies.add ("System.Data.dll");//compiler proxy class CompilerResults CR = ICC. CompileAssemblyFromDom (Cplist, CCU); if (true = = Cr. errors.haserrors) {System.Text.StringBuilder sb = new System.Text.StringBuilder (); foreach (System.CodeDom.Compiler.CompilerError ce in CR. Errors) {sb. Append (CE. ToString ()); Sb. Append (System.Environment.NewLine); } throw new Exception (sb.) ToString ()); }//Generate proxy instance and call method System.Reflection.Assembly Assembly = cr.compiledassembly; Type[] Types = assembly. GetTypes (); Type t = types[0]; Object obj = activator.createinstance (t); System.Reflection.MethodInfo mi = t.getmethod (methodname); Return MI. Invoke (obj, args); } catch (Exception ex) {} return null; } #endregion///////////////Interface parameter collection package//private static byte[] Paramda Taconvert (Dictionary dctparam) {if (Dctparam = = null) return null; Try {Encoding requestencoding = system.text.encoding.utf8;//Character Set StringBuilder buffer = new StringBuilder (); int i = 0; foreach (string key in Dctparam.keys) {if (i > 0) { Buffer. AppendFormat ("&{0}={1}", Key, (Dctparam[key])); } else {buffer. AppendFormat ("{0}={1}", Key, (Dctparam[key])); } i++; } string postdata = buffer. ToString (); byte[] data = requestencoding.getbytes (buffer. ToString ()); return data; } catch (Exception ex) {} return null; }////////////Response object///</returns> public static string Readhtt Pwebresponse (HttpWebResponse HttpWebResponse) {Stream responsestream = null; StreamReader sreader = null; String value = null; try {//Get response stream responsestream = Httpwebresponse.getresponsestream (); Docking response stream (in "Utf-8" character set) Sreader = new StreamReader (Responsestream, encoding.getencoding ("Utf-8")); Start reading data value = Sreader.readtoend (); } catch (Exception ee) {throw EE; } finally {//force close if (sreader! = null) { Sreader.close (); } if (Responsestream! = null) {responsestream.close (); } if (HttpWebResponse! = null) {httpwebresponse.close (); }} return value; } PubLic static string Encodepostdata (String Data) {string encodedata = Httputility.urldecode (data); return encodedata; } }}

  

HTTP request post and get call interface and reflection dynamic call WebServices class

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.