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
        }
    }

  

上一篇:fiddler 图片下载


下一篇:elasticsearch head插件无法显示数据问题