首页 > 其他分享 >HttpHelper

HttpHelper

时间:2024-03-23 18:12:04浏览次数:29  
标签:contentType string headers url HttpHelper application null

    public static class HttpHelper
    {
        //private static LogHelper Log { get; } = new LogHelper("HttpHelper");

        /// <summary>
        /// 发起POST同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>        
        /// <returns></returns>
        public static string Post(string url, string postData = null, string contentType = "application/json", int timeout = 30, Dictionary<string, string> headers = null, bool errorException = false)
        {
            postData = postData ?? "";

            using (var client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeout);
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                using (var httpContent = new StringContent(postData, Encoding.UTF8))
                {
                    if (contentType != null)
                    {
                        httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                    }

                    try
                    {
                        var response = client.PostAsync(url, httpContent).Result;
                        return response.Content.ReadAsStringAsync().Result;
                    }
                    catch (Exception ex)
                    {
                        if (errorException)
                        {
                            throw ex;
                        }

                        //Log.Error(ex);

                        return string.Empty;
                    }
                }
            }
        }


        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>        
        /// <returns></returns>
        public static async Task<string> PostAsync(string url, string postData = null, string contentType = "application/json", int timeout = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";

            using (var client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeout);
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                {
                    if (contentType != null)
                    {
                        httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                    }

                    try
                    {
                        var response = await client.PostAsync(url, httpContent);
                        return await response.Content.ReadAsStringAsync();
                    }
                    catch (Exception ex)
                    {
                        //Log.Error(ex);

                        return string.Empty;
                    }


                }
            }
        }

        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string Get(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                if (contentType != null)
                {
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                }
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                try
                {
                    var response = client.GetAsync(url).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
                catch (Exception ex)
                {
                    //Log.Error(ex);

                    return string.Empty;
                }
            }
        }

        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string Get(string url, HttpClientHandler clientHandler, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            using (var client = new HttpClient(clientHandler))
            {
                if (contentType != null)
                {
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                }
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                try
                {
                    var response = client.GetAsync(url).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
                catch (Exception ex)
                {
                    //Log.Error(ex);

                    return string.Empty;
                }
            }
        }

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<string> GetAsync(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            using (var client = new HttpClient())
            {
                if (contentType != null)
                {
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                }
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                try
                {
                    var response = await client.GetAsync(url);
                    return await response.Content.ReadAsStringAsync();
                }
                catch (Exception ex)
                {
                    //Log.Error(ex);

                    return string.Empty;
                }

            }
        }



        /// <summary>
        /// 发起POST同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>        
        /// <returns></returns>
        //public static T Post<T>(string url, string postData = null, string contentType = "application/json", int timeout = 30, Dictionary<string, string> headers = null)
        //{
        //    return Post(url, postData, contentType, timeout, headers).ToEntity<T>();
        //}


        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>        
        /// <returns></returns>
        //public static async Task<T> PostAsync<T>(string url, string postData = null, string contentType = "application/json", int timeout = 30, Dictionary<string, string> headers = null)
        //{
        //    var res = await PostAsync(url, postData, contentType, timeout, headers);
        //    return res.ToEntity<T>();
        //}

        public static string PostResponse(string url, string postData, string strContentType, out string statusCode)
        {
            if (url.StartsWith("https"))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            }

            var httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue(strContentType)
            {
                CharSet = "utf-8"
            };

            var httpClient = new HttpClient();
            //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

            var response = httpClient.PostAsync(url, httpContent).Result;

            statusCode = response.StatusCode.ToString();
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result;
            }

            return null;
        }
        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        //public static T Get<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        //{
        //    return Get(url, contentType, headers).ToEntity<T>();
        //}

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        //public static async Task<T> GetAsync<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        //{
        //    var res = await GetAsync(url, contentType, headers);
        //    return res.ToEntity<T>();
        //}
    }

 

标签:contentType,string,headers,url,HttpHelper,application,null
From: https://www.cnblogs.com/tiancaige/p/18091488

相关文章

  • 再也不用写请求HttpHelper了,HttpClient帮助你
    前言在C#7.1之后,net推出HttpClient类代替WebRequest,HttpWebRequest,ServicePoint,andWebClient,先来看下他们在以前的作用HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的一种方式ServicePoint提供HTTP连接的连接管理WebClient提供用于将数据发送到由......
  • HttpHelper
    publicclassHttpHelpe{publicstaticasyncTask<T>GetAsync<T>(stringurl,stringpostData=null,stringcontentType=null,inttimeOut=30,Dictionary<string,string>headers=null){returnawaitRequestAsync<T......
  • WebForm之企业微信开发(1)——准备httphelper
    usingSystem;usingSystem.IO;usingSystem.Net;usingSystem.Text;publicclassHttpHelper{///<summary>///发起一个HTTP请求(以POS......
  • C#实现HTTP访问类HttpHelper
    在项目开发过程中,我们经常会访问第三方接口,如我们需要接入的第三方接口是WebAPI,这时候我们就需要使用HttpHelper调用远程接口了。示例中的HttpHelper类使用Log4Net记录了......