HttpHelper之我見

來源:互聯網
上載者:User

標籤:request   ict   settings   請求   post   amp   .net   display   nal   

       前幾月一直用一個Http的訪問類去調用WebApi,說句實話最開始沒覺有什麼,一是技術老,二是覺得比較簡單,但是最近我一直關注云開發和AI這塊兒微軟技術,看到雲平台叫用API大多類似,所以回想這個早年的調用方式,感覺有老湯燉肉之感,實用又有價值,可以作為認識調用API的學習和使用,回味無窮。

    

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Net.Security;using System.Security.Cryptography.X509Certificates;using System.Text;using System.Web;namespace Bussiness.Helper{    public class HttpHelper    {        /// <summary>          /// 建立GET方式的HTTP請求          /// </summary>          public static HttpWebResponse CreateGetHttpResponse(string url, int timeout, string userAgent, CookieCollection cookies)        {            HttpWebRequest request = null;            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))            {                //對服務端認證進行有效性校正(非第三方權威機構頒發的認證,如自己產生的,不進行驗證,這裡返回true)                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);                request = WebRequest.Create(url) as HttpWebRequest;                request.ProtocolVersion = HttpVersion.Version10;    //http版本,預設是1.1,這裡設定為1.0            }            else            {                request = WebRequest.Create(url) as HttpWebRequest;                            }            request.Method = "GET";            request.Headers.Add("Origin", "http://" + request.Host);            //設定代理UserAgent和逾時            //request.UserAgent = userAgent;            //request.Timeout = timeout;            if (cookies != null)            {                request.CookieContainer = new CookieContainer();                request.CookieContainer.Add(cookies);            }            return request.GetResponse() as HttpWebResponse;        }        /// <summary>          /// 建立POST方式的HTTP請求          /// </summary>          public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)        {            HttpWebRequest request = null;            //如果是發送HTTPS請求              if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))            {                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);                request = WebRequest.Create(url) as HttpWebRequest;                //request.ProtocolVersion = HttpVersion.Version10;            }            else            {                request = WebRequest.Create(url) as HttpWebRequest;            }            request.Method = "POST";            request.ContentType = "application/x-www-form-urlencoded";            //設定代理UserAgent和逾時            //request.UserAgent = userAgent;            //request.Timeout = timeout;             if (cookies != null)            {                request.CookieContainer = new CookieContainer();                request.CookieContainer.Add(cookies);            }            //發送POST資料              if (!(parameters == null || parameters.Count == 0))            {                StringBuilder buffer = new StringBuilder();                int i = 0;                foreach (string key in parameters.Keys)                {                    if (i > 0)                    {                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);                    }                    else                    {                        buffer.AppendFormat("{0}={1}", key, parameters[key]);                        i++;                    }                }                //byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());                using (Stream stream = request.GetRequestStream())                {                    stream.Write(data, 0, data.Length);                }            }            string[] values = request.Headers.GetValues("Content-Type");            return request.GetResponse() as HttpWebResponse;        }        /// <summary>        /// 擷取請求的資料        /// </summary>        public static string GetResponseString(HttpWebResponse webresponse)        {            var result = string.Empty;            using (Stream s = webresponse.GetResponseStream())            {                StreamReader reader = new StreamReader(s, Encoding.UTF8);                result = reader.ReadToEnd();            }            return result;        }        /// <summary>        /// 驗證認證        /// </summary>        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)        {            if (errors == SslPolicyErrors.None)                return true;            return false;        }    }}
View Code

 

特備提示:

亂碼現象,注意改這裡:

//byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());

調用方式:

Dictionary<String, String> pList = new Dictionary<String, String>();pList.Add("Location", userLog.Location);pList.Add("Name", userLog.Name);ResultModel resultModel = new ResultModel();var apiDomain = ConfigurationManager.AppSettings["ApiDomain"];var url = @"" + apiDomain + "/api/AD/DeleteOneUser";// var url = @"" + apiDomain + "/api/AD/GetEmail";try{var response = HttpHelper.CreatePostHttpResponse(url, pList, 0, string.Empty, null);var info = HttpHelper.GetResponseString(response).Replace("\\", "");//info = info.Substring(1, info.Length - 2);//string intoStr = "{" + info + "}";resultModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultModel>(info);}catch(){}
View Code

 

HttpHelper之我見

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.