.net HttpClinetHelper工具类

using PCITC.Mobile.Manage.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;

namespace DMCWebAPI.Tools
{
    public static class HttpClinetHelper
    {
        public static Log4NetToDatabase.LogMessage LogMes { get; set; }

        public static string NeedLog = string.IsNullOrEmpty(ConfigurationManager.AppSettings["needLog"]) ? "" : ConfigurationManager.AppSettings["needLog"];//是否数据库需要记录日志信息
          

         /// <summary>
        /// Post提交对象,无返回值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data">Post的对象</param>
        /// <param name="url">服务地址</param>
        public static void Post<T>(T data,string url)
        {
            Post(data, url, null);
        }

        /// <summary>
        /// Post提交,无返回值
        /// </summary>
        /// <param name="url"></param>
        public static void Post(string url)
        {
            Post<object>(null, url, null);
        }


        /// <summary>
        ///  Post提交对象,返回值类型为V
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="data"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static V Post<T,V>(T data,string url)
        {
            return Post<T,V>(data, url, null);
        }

        /// <summary>
        /// Post提交,返回值类型为V
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="data"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static V Post<V>(string url)
        {
            return Post<object, V>(null, url, null);
        }

        /// <summary>
        /// Get获取
        /// </summary>
        /// <param name="url">服务地址</param>
        public static void Get(string url)
        {
            Get(url, null);
            
        }


        /// <summary>
        /// get获取
        /// </summary>
        /// <typeparam name="T">返回的数据类型</typeparam>
        /// <param name="url">服务地址</param>
        /// <returns></returns>
        public static T Get<T>(string url)
        {
            return Get<T>(url,null);

        }


        /// <summary>
        /// Post提交对象,无返回值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data">Post的对象</param>
        /// <param name="url">服务地址</param>
        public static void Post<T>(T data, string url, Dictionary<string, string> httpHeaders)
        {
            HttpResponseMessage response = null;
            StringContent httpContent = null;

            if (data != null)
            {
                //var json = JsonSerializerHelper.Serializer(data);
                var json = Tools.JSONHelper.SerializeToJson(data);
                httpContent = new StringContent(json, new UTF8Encoding(), "application/json");
            }

            using (HttpClient client = new HttpClient())
            {
                if (httpHeaders != null)
                {
                    if (httpContent!=null)
                    {
                        foreach (var headerItem in httpHeaders)
                        {
                            httpContent.Headers.Add(headerItem.Key, headerItem.Value);
                        }
                    }
                    else
                    {
                        foreach (var headerItem in httpHeaders)
                        {
                            client.DefaultRequestHeaders.Add(headerItem.Key, headerItem.Value);
                        }
                    }
                }
                response = client.PostAsync(url, httpContent).Result;
                //Logger.WriteLog("SerialNumberServiceProxy StatusCode:"+response.StatusCode.ToString(), System.Diagnostics.EventLogEntryType.Warning);
                if (!response.IsSuccessStatusCode)
                {
                    //Logger.WriteLog(response.Content.ReadAsStringAsync().Result, System.Diagnostics.EventLogEntryType.Error);
                    ErrorMessage errorResult = null;
                    try
                    {
                        errorResult = response.Content.ReadAsAsync<ErrorMessage>().Result;
                    }
                    catch
                    {
                        using (var stream = response.Content.ReadAsStreamAsync().Result)
                        {
                            byte[] arrayByte = new byte[stream.Length];
                            stream.Read(arrayByte, 0, (int)stream.Length);
                            throw new Exception(new UTF8Encoding().GetString(arrayByte));
                        }

                    }
                    if (errorResult != null)
                    {
                        LogMes = new Log4NetToDatabase.LogMessage("Post<T>:Code:" + errorResult.Code + ",Message:" + errorResult.Message, "DefaultCode");
                        LogCommon.ilogDebugDb.Debug(LogMes);
                    }
                }
            }
        }


        public static string PostJSON(string  jsonData, string url, Dictionary<string, string> httpHeaders)
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            HttpResponseMessage response = null;
            StringContent httpContent = null;

            if (jsonData != null)
            {
                httpContent = new StringContent(jsonData, new UTF8Encoding(), "application/json");
            }

            using (HttpClient client = new HttpClient())
            {
                if (httpHeaders != null)
                {
                    if (httpContent != null)
                    {
                        foreach (var headerItem in httpHeaders)
                        {
                            httpContent.Headers.Add(headerItem.Key, headerItem.Value);
                        }
                    }
                    else
                    {
                        foreach (var headerItem in httpHeaders)
                        {
                            client.DefaultRequestHeaders.Add(headerItem.Key, headerItem.Value);
                        }
                    }
                }
                response = client.PostAsync(url, httpContent).Result;
                //Logger.WriteLog("SerialNumberServiceProxy StatusCode:"+response.StatusCode.ToString(), System.Diagnostics.EventLogEntryType.Warning);
                if (!response.IsSuccessStatusCode)
                {
                    //Logger.WriteLog(response.Content.ReadAsStringAsync().Result, System.Diagnostics.EventLogEntryType.Error);
                    ErrorMessage errorResult = null;
                    try
                    {
                        errorResult = response.Content.ReadAsAsync<ErrorMessage>().Result;
                    }
                    catch
                    {
                        using (var stream = response.Content.ReadAsStreamAsync().Result)
                        {
                            byte[] arrayByte = new byte[stream.Length];
                            stream.Read(arrayByte, 0, (int)stream.Length);
                            throw new Exception(new UTF8Encoding().GetString(arrayByte));
                        }

                    }
                    if (errorResult != null)
                    {
                        LogMes = new Log4NetToDatabase.LogMessage("Post<T>:Code:" + errorResult.Code + ",Message:" + errorResult.Message, "DefaultCode");
                        LogCommon.ilogDebugDb.Debug(LogMes);
                    }
                    return errorResult.Message;
                }
                else 
                {
                    return "true";
                }
            }
        }


        /// <summary>
        /// Post提交对象,无内容,无返回值
        /// </summary>
        /// <param name="url">服务地址</param>
        /// <param name="httpHeaders">http头信息</param>
        public static void Post(string url, Dictionary<string, string> httpHeaders)
        {
            Post<object>(null,url,httpHeaders);
        }



        /// <summary>
        ///  Post提交对象,返回值类型为V
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="data"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static V Post<T, V>(T data, string url, Dictionary<string, string> httpHeaders)
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

            V result = default(V);

            StringContent httpContent = null;

            if (data != null)
            {
                var json = Tools.JSONHelper.SerializeToJson(data);
                //var json = JsonSerializerHelper.Serializer(data);
                httpContent = new StringContent(json, new UTF8Encoding(), "application/json");
            }


            using (HttpClient client = new HttpClient())
            {
                if (httpHeaders != null)
                {
                    if (httpContent != null)
                    {
                        foreach (var headerItem in httpHeaders)
                        {
                            httpContent.Headers.Add(headerItem.Key, headerItem.Value);
                        }
                    }
                    else
                    {
                        foreach (var headerItem in httpHeaders)
                        {
                            client.DefaultRequestHeaders.Add(headerItem.Key, headerItem.Value);
                        }
                    }
                }

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

                //Logger.WriteLog("SerialNumberServiceProxy StatusCode:"+response.StatusCode.ToString(), System.Diagnostics.EventLogEntryType.Warning);
                if (!response.IsSuccessStatusCode)
                {
                    //Logger.WriteLog(response.Content.ReadAsStringAsync().Result, System.Diagnostics.EventLogEntryType.Error);
                    ErrorMessage errorResult = null;
                    try
                    {
                        errorResult = response.Content.ReadAsAsync<ErrorMessage>().Result;
                    }
                    catch
                    {
                        using (var stream = response.Content.ReadAsStreamAsync().Result)
                        {
                            byte[] arrayByte = new byte[stream.Length];
                            stream.Read(arrayByte, 0, (int)stream.Length);
                            throw new Exception(new UTF8Encoding().GetString(arrayByte));
                        }
                    }
                    if (errorResult != null)
                    {
                        //throw new UtilityException(errorResult.Code, errorResult.Message);
                        throw new Exception("1");
                    }
                }
                else
                {
                    return response.Content.ReadAsAsync<V>().Result;
                }

            }


            return result;
        }

        public static V Post<V>(string url, Dictionary<string, string> httpHeaders)
        {
            return Post<object,V>(null,url,httpHeaders);
        }



        /// <summary>
        /// Get获取
        /// </summary>
        /// <param name="url">服务地址</param>
        public static void Get(string url, Dictionary<string, string> httpHeaders)
        {
            using (HttpClient client = new HttpClient())
            {
                if (httpHeaders != null)
                {
                    foreach (var headerItem in httpHeaders)
                    {
                        client.DefaultRequestHeaders.Add(headerItem.Key, headerItem.Value);
                    }
                }
                
                var response = client.GetAsync(url).Result;

                //Logger.WriteLog("SerialNumberServiceProxy StatusCode:"+response.StatusCode.ToString(), System.Diagnostics.EventLogEntryType.Warning);
                if (!response.IsSuccessStatusCode)
                {
                    //Logger.WriteLog(response.Content.ReadAsStringAsync().Result, System.Diagnostics.EventLogEntryType.Error);
                    ErrorMessage errorResult = null;
                    try
                    {
                        errorResult = response.Content.ReadAsAsync<ErrorMessage>().Result;
                    }
                    catch
                    {
                        using (var stream = response.Content.ReadAsStreamAsync().Result)
                        {
                            byte[] arrayByte = new byte[stream.Length];
                            stream.Read(arrayByte, 0, (int)stream.Length);
                            throw new Exception(new UTF8Encoding().GetString(arrayByte));
                        }

                    }
                    if (errorResult != null)
                    {
                        throw new Exception("1");
                        //throw new UtilityException(errorResult.Code, errorResult.Message);
                    }
                }

            }

        }


        /// <summary>
        /// get获取
        /// </summary>
        /// <typeparam name="T">返回的数据类型</typeparam>
        /// <param name="url">服务地址</param>
        /// <returns></returns>
        public static T Get<T>(string url, Dictionary<string, string> httpHeaders)
        {
            T result = default(T);
            using (HttpClient client = new HttpClient())
            {
                if (httpHeaders != null)
                {
                    foreach (var headerItem in httpHeaders)
                    {
                        client.DefaultRequestHeaders.Add(headerItem.Key, headerItem.Value);
                    }
                }

                var response = client.GetAsync(url).Result;

                //Logger.WriteLog("SerialNumberServiceProxy StatusCode:"+response.StatusCode.ToString(), System.Diagnostics.EventLogEntryType.Warning);
                if (!response.IsSuccessStatusCode)
                {
                    //Logger.WriteLog(response.Content.ReadAsStringAsync().Result, System.Diagnostics.EventLogEntryType.Error);
                    ErrorMessage errorResult = null;
                    try
                    {
                        errorResult = response.Content.ReadAsAsync<ErrorMessage>().Result;
                    }
                    catch
                    {
                        using (var stream = response.Content.ReadAsStreamAsync().Result)
                        {
                            byte[] arrayByte = new byte[stream.Length];
                            stream.Read(arrayByte, 0, (int)stream.Length);
                            throw new Exception(new UTF8Encoding().GetString(arrayByte));
                        }

                    }
                    if (errorResult != null)
                    {
                        throw new Exception("1");
                        //throw new UtilityException(errorResult.Code, errorResult.Message);
                    }
                }
                else
                {
                    return response.Content.ReadAsAsync<T>().Result;
                }

            }

            return result;

        }

    }
}

 

转载于:https://www.cnblogs.com/fjinlong/p/8018077.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值