http請求POST和GET調用介面以及反射動態調用Webservices類

來源:互聯網
上載者:User

標籤:強制   產生   isnull   out   傳參數   import   service   tab   user   

此代碼是API、WebSrvices動態調用的類,做介面調用時很實用。

Webservices動態調用使用反射的方式很大的缺點是效率低,若有更好的動態調用webservices方法,望各位仁兄不吝貼上代碼。

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;/********************** 描述:提供http、POST和GET、Webservices動態訪問遠程介面 * *******************/namespace Demo{    public static class HttpHelper    {        ///          /// 有關HTTP請求的輔助類        ///         private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";//瀏覽器         private static Encoding requestEncoding = System.Text.Encoding.UTF8;//字元集   #region 建立GET方式的HTTP請求        ///        /// 建立GET方式的HTTP請求           ///        /// 介面URL        /// 介面URL的參數        /// 調用介面返回的資訊        ///        public static bool HttpGet(string url, Dictionary dctParam, out string HttpWebResponseString)        {            if (string.IsNullOrEmpty(url))            {                throw new ArgumentNullException("url");            }            HttpWebResponseString = "";             HttpWebRequest request = null;            Stream stream = null;//用於傳參數的流             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";//傳輸方式                  request.ContentType = "application/x-www-form-urlencoded";//協議                request.UserAgent = DefaultUserAgent;//請求的用戶端瀏覽器資訊,預設IE                 request.Timeout = 6000;//逾時時間,寫死6秒                request.KeepAlive = false;                //DefaultConnectionLimit是預設的2,而當前的Http的connection用完了,導致後續的GetResponse或GetRequestStream逾時死掉                System.Net.ServicePointManager.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 建立POST方式的HTTP請求 /// /// 建立POST方式的HTTP請求 /// /// 介面URL /// 介面URL的參數 /// 調用介面返回的資訊 /// public static bool HttpPost(string url, Dictionary dctParam, out string HttpWebResponseString) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } HttpWebResponseString = ""; HttpWebRequest request = null; Stream stream = null;//用於傳參數的流 try { url = EncodePostData(url); request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST";//傳輸方式 request.ContentType = "application/x-www-form-urlencoded";//協議 request.UserAgent = DefaultUserAgent;//請求的用戶端瀏覽器資訊,預設IE request.Timeout = 6000;//逾時時間,寫死6秒 //DefaultConnectionLimit是預設的2,而當前的Http的connection用完了,導致後續的GetResponse或GetRequestStream逾時死掉 System.Net.ServicePointManager.DefaultConnectionLimit = 50; request.ServicePoint.Expect100Continue = false; //如果需求POST傳資料,轉換成utf-8編碼 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 (Exception ee) { HttpWebResponseString = ee.ToString(); return false; } finally { if (stream != null) { stream.Close(); } } } #endregion #region 反射動態調用WebServices /// /// 反射動態調用WebServices /// /// Webservices地址,以?WSDL結尾 /// 調用的方法 /// 調用方法的參數 /// public static object InvokeWebService(string url, string methodname, object[] args) { string @namespace = "Demo";//本頁的命名空間 try { //擷取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); //產生用戶端代理類代碼 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); CSharpCodeProvider icc = new CSharpCodeProvider(); //設定編譯參數 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");//編譯代理類 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()); } //組建代理程式執行個體,並調用方法 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 /// /// 介面參數轉換 /// /// 介面參數集合包 /// private static byte[] ParamDataConvert(Dictionary dctParam) { if (dctParam == null) return null; try { Encoding requestEncoding = System.Text.Encoding.UTF8;//字元集 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; } /// /// 擷取資料 /// /// 響應對象 /// </returns> public static string ReadHttpWebResponse(HttpWebResponse HttpWebResponse) { Stream responseStream = null; StreamReader sReader = null; String value = null; try { // 擷取響應流 responseStream = HttpWebResponse.GetResponseStream(); // 對接響應流(以"utf-8"字元集) sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 開始讀取資料 value = sReader.ReadToEnd(); } catch (Exception ee) { throw ee; } finally { //強制關閉 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請求POST和GET調用介面以及反射動態調用Webservices類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.