欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

httpClient常用类整理

程序员文章站 2024-01-21 19:54:16
...

```csharp
namespace CoreHuaXia.Common
{
    #region Using

    using global::System;
    using global::System.Collections.Generic;
    using global::System.Linq;
    using global::System.Net.Http;
    using global::System.Net.Http.Headers;
    using global::System.Reflection;

    using Newtonsoft.Json;
    using System.IO;

    #endregion

    public static class LightingHttpClient
    {
        internal static readonly HttpClient L_HttpClient;

        static LightingHttpClient()
        {
            L_HttpClient = new HttpClient();
            L_HttpClient.Timeout = TimeSpan.FromSeconds(120);
        }
        static int HttpCount = 0;
        public static string Get(string url, object urldatas, Action<Exception> error = null, object headerdatas = null)
        {
            string content = "";

            List<Tuple<string, string>> parlist = ObjectPropertiesConvertKeyValuePirs(urldatas);
            List<Tuple<string, string>> headerlist = ObjectPropertiesConvertKeyValuePirs(headerdatas);

            url = ConvertToUrl(url, parlist);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            foreach (Tuple<string, string> header in headerlist)
            {
                request.Headers.Add(header.Item1, header.Item2);
            }

            request.Headers.Add("Connection", "close");
            try
            {
                HttpResponseMessage response = L_HttpClient.SendAsync(request).Result;

                if ((Action<Exception>)null != error)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        //不成功再执行一次
                        try
                        {
                            response.EnsureSuccessStatusCode();
                        }
                        catch (HttpRequestException e)
                        {
                            error(e);
                        }
                    }
                    else
                    {
                        content = response.Content.ReadAsStringAsync().Result;
                    }
                }
            }
            catch (Exception e)
            {

                error(e);
            }

            return content;
        }

        public static string Post(string url, object datas, Action<Exception> error = null, object headerdatas = null)
        {
            string content = "";
            List<Tuple<string, string>> parlist = ObjectPropertiesConvertKeyValuePirs(datas);
            List<Tuple<string, string>> headerlist = ObjectPropertiesConvertKeyValuePirs(headerdatas);

            List<KeyValuePair<string, string>> urlpars = ConvertToKeyValuePair(parlist);

            FormUrlEncodedContent urlcontent = new FormUrlEncodedContent(urlpars);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);

            foreach (Tuple<string, string> header in headerlist)
            {
                request.Headers.Add(header.Item1, header.Item2);
            }

            request.Headers.Add("Connection", "close");

            request.Content = urlcontent;

            try
            {
                HttpResponseMessage response = L_HttpClient.SendAsync(request).Result;

                if ((Action<Exception>)null != error)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        try
                        {
                            response.EnsureSuccessStatusCode();
                        }
                        catch (HttpRequestException e)
                        {
                            error(e);
                        }
                    }
                    else
                    {
                        content = response.Content.ReadAsStringAsync().Result;
                    }
                }
            }
            catch (Exception e)
            {
                error(e);
            }

            return content;
        }

        public static string Put(string url, object datas, Action<Exception> error = null, object headerdatas = null)
        {
            string content = "";
            List<Tuple<string, string>> parlist = ObjectPropertiesConvertKeyValuePirs(datas);
            List<Tuple<string, string>> headerlist = ObjectPropertiesConvertKeyValuePirs(headerdatas);

            List<KeyValuePair<string, string>> urlpars = ConvertToKeyValuePair(parlist);

            FormUrlEncodedContent urlcontent = new FormUrlEncodedContent(urlpars);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, url);

            foreach (Tuple<string, string> header in headerlist)
            {
                request.Headers.Add(header.Item1, header.Item2);
            }

            request.Headers.Add("Connection", "close");

            request.Content = urlcontent;

            try
            {
                HttpResponseMessage response = L_HttpClient.SendAsync(request).Result;

                if ((Action<Exception>)null != error)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        try
                        {
                            response.EnsureSuccessStatusCode();
                        }
                        catch (HttpRequestException e)
                        {
                            error(e);
                        }
                    }
                    else
                    {
                        content = response.Content.ReadAsStringAsync().Result;
                    }
                }
            }
            catch (Exception e)
            {
                error(e);
            }

            return content;
        }

        public static string Delete(string url, object datas, Action<Exception> error = null, object headerdatas = null)
        {
            string content = "";
            List<Tuple<string, string>> parlist = ObjectPropertiesConvertKeyValuePirs(datas);
            List<Tuple<string, string>> headerlist = ObjectPropertiesConvertKeyValuePirs(headerdatas);

            url = ConvertToUrl(url, parlist);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, url);

            foreach (Tuple<string, string> header in headerlist)
            {
                request.Headers.Add(header.Item1, header.Item2);
            }

            request.Headers.Add("Connection", "close");

            try
            {
                HttpResponseMessage response = L_HttpClient.SendAsync(request).Result;

                if ((Action<Exception>)null != error)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        try
                        {
                            response.EnsureSuccessStatusCode();
                        }
                        catch (HttpRequestException e)
                        {
                            error(e);
                        }
                    }
                    else
                    {
                        content = response.Content.ReadAsStringAsync().Result;
                    }
                }
            }
            catch (Exception e)
            {
                error(e);
            }

            return content;
        }

        public static string PostAsJSON<T>(string url, T value, Action<Exception> error = null, object headerdatas = null)
        {
            string content = "";
            List<Tuple<string, string>> headerlist = ObjectPropertiesConvertKeyValuePirs(headerdatas);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);

            foreach (Tuple<string, string> header in headerlist)
            {
                request.Headers.Add(header.Item1, header.Item2);
            }

            request.Headers.Add("Connection", "close");

            StringContent stringcontent = new StringContent(JsonConvert.SerializeObject(value));
            stringcontent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            request.Content = stringcontent;
            try
            {
                HttpResponseMessage response = L_HttpClient.SendAsync(request).Result;

                if ((Action<Exception>)null != error)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        try
                        {
                            response.EnsureSuccessStatusCode();
                        }
                        catch (HttpRequestException e)
                        {
                            error(e);
                        }
                    }
                    else
                    {
                        content = response.Content.ReadAsStringAsync().Result;
                    }
                }
            }
            catch (Exception e)
            {
                error(e);
            }
            return content;
        }
        
        public static string Form(string url, string filePath, Action<Exception> error = null, object headerdatas = null)
        {
            string content = "";
            List<Tuple<string, string>> headerlist = ObjectPropertiesConvertKeyValuePirs(headerdatas);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);

            foreach (Tuple<string, string> header in headerlist)
            {
                request.Headers.Add(header.Item1, header.Item2);
            }
            request.Headers.Add("Connection", "keep-alive");
            MultipartFormDataContent mContent = new MultipartFormDataContent();
            if (File.Exists(filePath))
            {
                StreamContent fileContent = new StreamContent((Stream)new MemoryStream(File.ReadAllBytes(filePath)));
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    FileName = Path.GetFileName("huaxia." + filePath.Substring(filePath.LastIndexOf("."))),
                    Name = "file"
                };
                fileContent.Headers.Add("ContentType", "application/octet-stream");

                mContent.Add(fileContent);
                request.Content = mContent;
            }
            try
            {
                HttpResponseMessage response = L_HttpClient.SendAsync(request).Result;
                if ((Action<Exception>)null != error)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        try
                        {
                            response.EnsureSuccessStatusCode();
                        }
                        catch (HttpRequestException e)
                        {
                            error(e);
                        }
                    }
                    else
                    {
                        content = response.Content.ReadAsStringAsync().Result;
                    }
                }
            }
            catch (Exception e)
            {
                error(e);
            }

            return content;
        }

        public static string PostAsJSONNonSingleton<T>(HttpClient myhttpClient, string url, T value, Action<Exception> error = null, object headerdatas = null)
        {
            string content = "";
            List<Tuple<string, string>> headerlist = ObjectPropertiesConvertKeyValuePirs(headerdatas);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);

            foreach (Tuple<string, string> header in headerlist)
            {
                request.Headers.Add(header.Item1, header.Item2);
            }

            request.Headers.Add("Connection", "close");

            StringContent stringcontent = new StringContent(JsonConvert.SerializeObject(value));
            stringcontent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            request.Content = stringcontent;
            try
            {
                HttpResponseMessage response = myhttpClient.SendAsync(request).Result;

                if ((Action<Exception>)null != error)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        try
                        {
                            response.EnsureSuccessStatusCode();
                        }
                        catch (HttpRequestException e)
                        {
                            error(e);
                        }
                    }
                    else
                    {
                        content = response.Content.ReadAsStringAsync().Result;
                    }
                }
            }
            catch (Exception e)
            {
                error(e);
            }
            return content;
        }

        #region Private Methods

        private static List<Tuple<string, string>> ObjectPropertiesConvertKeyValuePirs(object obj)
        {
            List<Tuple<string, string>> parlist = new List<Tuple<string, string>>();

            if (null != obj)
            {
                PropertyInfo[] propertys = obj.GetType().GetProperties();

                foreach (PropertyInfo propertyinfo in propertys)
                {
                    if (typeof(string) == propertyinfo.PropertyType)
                    {
                        string pkey = propertyinfo.Name.Trim();
                        string pvalue = (propertyinfo.GetValue(obj) == null) ? "" : propertyinfo.GetValue(obj).ToString();

                        parlist.Add(new Tuple<string, string>(pkey, pvalue));
                    }
                }
            }

            return parlist;
        }

        private static List<KeyValuePair<string, string>> ConvertToKeyValuePair(List<Tuple<string, string>> from)
        {
            List<KeyValuePair<string, string>> to = new List<KeyValuePair<string, string>>(from.Count);

            to.AddRange(@from.Select(tuple => new KeyValuePair<string, string>(tuple.Item1, tuple.Item2)));

            return to;
        }

        private static string ConvertToUrl(string url, List<Tuple<string, string>> from)
        {
            return @from.Aggregate(url, (current, tuple) => current + (((current.Contains("?")) ? "&" : "?") + tuple.Item1 + "=" + tuple.Item2));
        }

        #endregion
    }
}

相关标签: core