• 00
  • :
  • 00
  • :
  • 00

http post get 类库 httphelper

  public class HttpHelper
    {

        /// <summary>
        /// 请求超时时间
        /// </summary>
        public static int TimeOut { get; set; } = 100 * 1000;
        private static HttpWebRequest GetRequest(string url)
        {
            System.Net.HttpWebRequest request;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                ServicePointManager.CheckCertificateRevocationList = false;
                ServicePointManager.DefaultConnectionLimit = 512;
                ServicePointManager.Expect100Continue = false;

                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
                request.KeepAlive = false;
            }
            else
            {
                request = (System.Net.HttpWebRequest)WebRequest.Create(url);
            }
            request.Timeout = TimeOut;
            return request;
        }
        /// <summary>
        /// 客户端统一提交数据
        /// </summary>
        /// <param name="url">WebAPI核心URL地址</param>
        /// <param name="data">提交的数据</param>
        /// <param name="contentType">指定request.ContentType</param>
        /// <returns>返回数据</returns>
        public static GZResponseDataModel Post(string url, string data, string contentType)
        {
            System.Net.HttpWebRequest request = GetRequest(url);
            request.Method = "POST";
            request.ContentType = contentType;// "application/json;charset=UTF-8";//POST必须使用JSON格式
            if (!String.IsNullOrEmpty(data))
            {
                string paraUrlCoded = data;
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = payload.Length;
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
            }
            return GetResponse(request);
        }


        private static GZResponseDataModel GetResponse(System.Net.HttpWebRequest request)
        {
            try
            {
                using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse())
                {
                    return GetResponse(response);
                }
            }
            catch (WebException ex)
            {
                var result = GetResponse(ex);


                return result;
            }
            catch (Exception ex)
            {
                GZResponseDataModel result = new GZResponseDataModel();
                result.Success = false;
                result.StatusCode = HttpStatusCode.BadRequest;
                result.Message = "请求过程中发生异常:" + ex.ToString();
                result.ExceptionStatus = WebExceptionStatus.UnknownError;

                return result;
            }
        }

        private static GZResponseDataModel GetResponse(WebResponse response)
        {
            string responseTxt = "";
            using (System.IO.Stream s = response.GetResponseStream())
            {
                using (StreamReader Reader = new StreamReader(s, Encoding.GetEncoding("utf-8")))
                {
                    responseTxt = Reader.ReadToEnd();
                }
            }
            if (response is HttpWebResponse)
            {
                HttpStatusCode statusCode = (response as HttpWebResponse).StatusCode;

                GZResponseDataModel result = new GZResponseDataModel()
                {
                    Success = statusCode == HttpStatusCode.OK,
                    StatusCode = statusCode,
                    ResponseText = responseTxt
                };
                return result;
            }
            throw new Exception("response不是HttpWebResponse,没有相应的处理类型");
        }


        private static GZResponseDataModel GetResponse(WebException webException)
        {

            var response = webException.Response;
            if (response == null)
            {
                GZResponseDataModel result = new GZResponseDataModel()
                {
                    Success = false,
                    StatusCode = HttpStatusCode.BadRequest,
                    ExceptionStatus = webException.Status,
                    Message = webException.Message
                };

                return result;


                //return;
            }
            string responseTxt = "";
            using (System.IO.Stream s = response.GetResponseStream())
            {
                using (StreamReader Reader = new StreamReader(s, Encoding.GetEncoding("utf-8")))
                {
                    responseTxt = Reader.ReadToEnd();
                }
            }
            if (response is HttpWebResponse)
            {
                HttpStatusCode statusCode = (response as HttpWebResponse).StatusCode;

                GZResponseDataModel result = new GZResponseDataModel()
                {
                    Success = statusCode == HttpStatusCode.OK,
                    StatusCode = statusCode,
                    ResponseText = responseTxt
                };
                return result;
            }
            throw new Exception("response不是HttpWebResponse,没有相应的处理类型");
        }


        public static GZResponseDataModel Get(string url)
        {
            System.Net.HttpWebRequest request = GetRequest(url);
            request.ContentType = "text/html";
            request.Method = "Get";

            return GetResponse(request);
        }

        public static GZResponseDataModel PostJson(string url, string data)
        {
            string contentType = "application/json;charset=UTF-8";

            return Post(url, data, contentType);
        }

        public static GZResponseDataModel PostForm(string url, string data)
        {
            string contentType = "application/x-www-form-urlencoded";

            return Post(url, data, contentType);
        }

        public static GZResponseDataModel PostForm(string url, System.Collections.Specialized.NameValueCollection PostVars)
        {
            string contentType = "application/x-www-form-urlencoded";
            List<string> data = new List<string>();
            foreach (string key in PostVars.AllKeys)
            {
                data.Add($"{key}={PostVars[key]}");
            }
            string strVal = String.Join("&", data.ToArray());

            return Post(url, strVal, contentType);
        }



        public static void PostTestFormValue()
        {
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            PostVars.Add("test", "value");
            PostVars.Add("cmd", "value");
            PostVars.Add("token", "value");
            PostForm("url", PostVars);
        }

    }

    public class GZResponseDataModel
    {
        public bool Success { get; set; }
        public HttpStatusCode StatusCode { get; set; }
        public WebExceptionStatus ExceptionStatus { get; set; }

        public string Message { get; set; }

        public string ResponseText { get; set; }

        public T ConvertObject<T>()
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(this.ResponseText);
        }
    }

 

posted @ 2021-01-08 18:34  Garson_Zhang  阅读(259)  评论(0编辑  收藏  举报