RequestHelper

 public class RequestHelper
    {
        #region  post 請求
        public static string HttpPost(string url, object data, Dictionary<string, string> headerDic = null, string contentType = "application/json")
        {
            return Request(url, data, "POST", headerDic, contentType);
        }

        public static T HttpPost<T>(string url, object data, Dictionary<string, string> headerDic = null, string contentType = "application/json")
        {
            return SerializeHelper.Deserialize<T>(HttpPost(url, data, headerDic, contentType));
        }
        #endregion

        #region  get請求
        public static T HttpGet<T>(string url, Dictionary<string, string> urlParameters = null, Dictionary<string, string> headerDic = null, string contentType = "application/json")
        {
            return SerializeHelper.Deserialize<T>(HttpGet(url, urlParameters, headerDic, contentType));
        }
        public static string HttpGet(string url, Dictionary<string, string> urlParameters = null, Dictionary<string, string> headerDic = null, string contentType = "application/json")
        {
            return Request(BuildQuery(url, urlParameters), null, "Get", headerDic, contentType);
        }
        #endregion

        #region 輔助方法   
        public static string Request(string url, object data, string method, Dictionary<string, string> headerDic, string contentType)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    //忽略證書認證錯誤處理的函數
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                    // 這裏設置了協議類型。 
                    //.net4.5及以上
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    //.net4.5及以下
                    // ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                    ServicePointManager.CheckCertificateRevocationList = true;
                    ServicePointManager.DefaultConnectionLimit = 100;
                    ServicePointManager.Expect100Continue = false;
                }
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;
                request.ContentType = contentType;
                //request.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                //增加下面兩個屬性即可  
                request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version10;

                request.AllowAutoRedirect = true;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                request.Accept = "*/*";

                AddHeaderInfo(request, headerDic);
                if (data != null)
                {
                    string paramData = string.Empty;
                    if (data.GetType() == typeof(String))
                    {
                        paramData = Convert.ToString(data);
                    }
                    else
                    {
                        paramData = SerializeHelper.ToJson(data);
                    }
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        using (StreamWriter swrite = new StreamWriter(requestStream))
                        {
                            swrite.Write(paramData);
                        }
                    }
                }

                using (response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader sread = new StreamReader(responseStream))
                        {

                            return sread.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }

        /// <summary>
        /// 添加請求頭信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="headerDic"></param>
        public static void AddHeaderInfo(HttpWebRequest request, Dictionary<string, string> headerDic)
        {
            if (headerDic != null)
            {
                foreach (var item in headerDic)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
            }
        }

        /// <summary>
        /// 組裝請求參數
        /// </summary>
        /// <param name="parameters">Key-Value形式請求參數字典</param>
        /// <returns>URL編碼後的請求數據</returns>
        public static string BuildQuery(string url, IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder(url);
            if (parameters != null)
            {
                bool hasParam = false;
                IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
                if (parameters.Count > 0)
                {
                    postData.Append("?");
                }
                while (dem.MoveNext())
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(dem.Current.Key);
                    postData.Append("=");
                    postData.Append(HttpUtility.UrlEncode(dem.Current.Value, Encoding.UTF8));
                    hasParam = true;
                }
            }
            return postData.ToString();
        }

        /// <summary>
        /// 獲取客戶端IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                return "0.0.0.0";
            }
            return result;
            #endregion
        }
    }

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章