httpClient常用类整理


```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
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值