HttpHelper

    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>();
        //}
    }

 

posted on 2024-03-23 17:56  RookieBoy666  阅读(5)  评论(0编辑  收藏  举报