【HttpHelper】HTTP Get和Post请求


2021-04-21版本:

支持get请求和post请求,

支持header设置

支持https请求

public class HttpHelper
{

    /// <summary>
    /// 请求超时时间
    /// </summary>
    public static int TimeOut { get; set; } = 100 * 1000;
    private static HttpWebRequest GetRequest(string url, System.Collections.Specialized.NameValueCollection header)
    {
        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;
        if (header != null)
        {
            foreach (var key in header.AllKeys)
            {
                request.Headers.Add(key, header[key]);
            }
        }
        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.Collections.Specialized.NameValueCollection header)
    {
        System.Net.HttpWebRequest request = GetRequest(url, header);
        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.Collections.Specialized.NameValueCollection header)
    {
        System.Net.HttpWebRequest request = GetRequest(url, header);
        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, null);
    }
    public static GZResponseDataModel PostJson(string url, string data, System.Collections.Specialized.NameValueCollection header)
    {
        string contentType = "application/json;charset=UTF-8";

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

        return Post(url, data, contentType, null);
    }
    public static GZResponseDataModel PostForm(string url, string data, System.Collections.Specialized.NameValueCollection header)
    {
        string contentType = "application/x-www-form-urlencoded";

        return Post(url, data, contentType, header);
    }
    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, null);
    }

    public static GZResponseDataModel PostForm(string url, System.Collections.Specialized.NameValueCollection PostVars, System.Collections.Specialized.NameValueCollection header)
    {
        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, header);
    }

}

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);
    }
}
GarsonZhang www.yesdotnet.com

 

版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
YES开发框架
上一篇:C#日志Log写入
评论列表

发表评论

评论内容
昵称:
关联文章

HttpHelperHTTP GetPost请求
C# HTTPHTTPS Get请求 Post 请求
.NET中大型项目开发必备(9)--http请求调用(PostGet)
Jquery请求API,AJax,Post,Get提交,失败,错误的处理
使用.NET 6开发TodoList应用(10)——实现DELETE请求以及HTTP请求幂等性
使用.NET 6开发TodoList应用(7)——使用AutoMapper实现GET请求
Http请求中Referer的设置,CEFSharp带Referer请求
使用.NET 6开发TodoList应用(6)——使用MediatR实现POST请求
C#HTTP请求RestSharp.RestClient发起https请求报错
解决 axios 跨域时,发送 post 请求前options 404
RestSharp请求https添加Cookie信息的正确姿势
使用.NET 6开发TodoList应用(19)——处理OPTIONHEAD请求
C#利用CefSharp的ChromiumWebBrowser发起Post请求
.net core MVC 使用 jquery ajax请求 Post json
Winform开启一个http服务,web服务
使用.NET 6开发TodoList应用(11)——使用FluentValidationMediatR实现接口请求验证
使用.NET 6开发TodoList应用(9)——实现PUT请求
同时多个请求_axios多并发请求
微信支付:header中的mchid与post payload中的mchid不匹配
ASP.NET Core 中读取Post Request.Body 的正确姿势