码迷,mamicode.com
首页 > Windows程序 > 详细

【C#】Http帮助类

时间:2019-05-24 01:08:47      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:trace   https   api   error   nbsp   json   concat   method   方式   

1、请求http帮助类

  

public class HttpHelper
    {
        private HttpClient _httpClient;
        private string _baseIPAddress;

        public HttpHelper(string ipaddress = "")
        {
            this._baseIPAddress = ipaddress;
            _httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) };
        }

        /// <summary>
        /// 创建带用户信息的请求客户端
        /// </summary>
        /// <param name="userName">用户账号</param>
        /// <param name="pwd">用户密码,当WebApi端不要求密码验证时,可传空串</param>
        /// <param name="uriString">The URI string.</param>
        public HttpHelper(string userName, string pwd = "", string uriString = "")
            : this(uriString)
        {
            if (!string.IsNullOrEmpty(userName))
            {
                _httpClient.DefaultRequestHeaders.Authorization = CreateBasicCredentials(userName, pwd);
            }
        }

        /// <summary>
        /// 创建带用户信息的请求客户端
        /// </summary>
        /// <param name="userName">用户账号</param>
        /// <param name="pwd">用户密码,当WebApi端不要求密码验证时,可传空串</param>
        /// <param name="uriString">The URI string.</param>
        private AuthenticationHeaderValue CreateBasicCredentials(string userName, string password)
        {
            string toEncode = userName + ":" + password;
            Encoding encoding = Encoding.GetEncoding("utf-8");
            byte[] toBase64 = encoding.GetBytes(toEncode);
            string parameter = Convert.ToBase64String(toBase64);

            return new AuthenticationHeaderValue("Basic", parameter);
        }

        /// <summary>
        /// 把请求的URL相对路径组合成绝对路径
        /// </summary>
        private string ConcatURL(string requestUrl)
        {
            return new Uri(_httpClient.BaseAddress, requestUrl).OriginalString;
        }

        /// <summary>
        /// Get请求数据
        ///   /// <para>最终以url参数的方式提交</para>
        /// </summary>
        /// <param name="parameters">参数字典,可为空</param>
        /// <param name="requestUri">例如/api/Files/UploadFile</param>
        /// <returns></returns>
        public string Get(Dictionary<string, string> parameters, string requestUri)
        {
            if (parameters != null)
            {
                var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
                requestUri = string.Concat(ConcatURL(requestUri), "?", strParam);
            }
            else

            {
                requestUri = ConcatURL(requestUri);
            }
            var result = _httpClient.GetStringAsync(requestUri);
            return result.Result;
        }

        /// <summary>
        /// 以json的方式Post数据 返回string类型
        /// <para>最终以json的方式放置在http体中</para>
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="requestUri">例如/api/Files/UploadFile</param>
        /// <returns></returns>
        public T Get<T>(Dictionary<string, string> parameters, string requestUri) where T : class
        {
            string jsonString = this.Get(parameters, requestUri);

            if (string.IsNullOrEmpty(jsonString))
                return null;

            return JsonHelper.Instance.Deserialize<T>(jsonString);
        }

        /// <summary>
        /// 提交字典类型的数据
        /// <para>最终以formurlencode的方式放置在http体中</para>
        /// </summary>
        /// <returns>System.String.</returns>
        public string PostDicObj(Dictionary<string, object> para, string requestUri)
        {
            Dictionary<string, string> temp = new Dictionary<string, string>();
            foreach (var item in para)
            {
                if (item.Value != null)
                {
                    if (item.Value.GetType().Name.ToLower() != "string")
                    {
                        temp.Add(item.Key, JsonHelper.Instance.Serialize(item.Value));
                    }
                    else
                    {
                        temp.Add(item.Key, item.Value.ToString());
                    }
                }
                else
                {
                    temp.Add(item.Key, "");
                }
            }

            return PostDic(temp, requestUri);
        }

        /// <summary>
        /// Post Dic数据
        /// <para>最终以formurlencode的方式放置在http体中</para>
        /// </summary>
        /// <returns>System.String.</returns>
        public string PostDic(Dictionary<string, string> temp, string requestUri)
        {
            HttpContent httpContent = new FormUrlEncodedContent(temp);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            return Post(requestUri, httpContent);
        }

        /// <summary>
        /// byte数据
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="requestUrl"></param>
        /// <returns></returns>
        public string PostByte(byte[] bytes, string requestUrl)
        {
            HttpContent content = new ByteArrayContent(bytes);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            return Post(requestUrl, content);
        }

        /// <summary>
        /// 以json的方式Post数据 返回string类型
        /// <para>最终以json的方式放置在http体中</para>
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="requestUri">例如/api/Files/UploadFile</param>
        /// <returns></returns>
        public string Post(object obj, string requestUri)
        {
            string request = string.Empty;
            if (obj != null)
                request = JsonHelper.Instance.Serialize(obj);
            HttpContent httpContent = new StringContent(request);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return Post(requestUri, httpContent);
        }

        public string Post(string requestUri, HttpContent content)
        {
            var result = _httpClient.PostAsync(requestUri, content);
            return result.Result.Content.ReadAsStringAsync().Result;
        }

        public string PostDic(Dictionary<string, string> temp, string requestUri,Action<string> action)
        {
            try
            {
                HttpContent httpContent = new FormUrlEncodedContent(temp);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                return Post(requestUri, httpContent);
            }
            catch (Exception ex)
            {
                action(ex.Message + ",堆栈信息:" + ex.StackTrace);
            }
            return string.Empty;
        }

        public string HttpPost(string url, string body, Action<string> action)
        {
            try
            {
                string contenttype = "application/x-www-form-urlencoded";

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = contenttype;

                byte[] btBodys = Encoding.UTF8.GetBytes(body);
                httpWebRequest.ContentLength = btBodys.Length;

                using (Stream newStream = httpWebRequest.GetRequestStream())
                {
                    // Send data.
                    newStream.Write(btBodys, 0, btBodys.Length);
                }

                // Get response
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                string result = reader.ReadToEnd();//得到结果
                reader.Close();
                httpWebResponse.Close();
                httpWebRequest.Abort();

                return result;
            }
            catch (Exception ex)
            {
                action(ex.Message+",堆栈信息:"+ex.StackTrace);
            }
            return string.Empty;
        }

        public static string HttpGet(string url, string httpToken,ref string message,DateTime IfModifiedSince = default(DateTime), Dictionary<string,string> headers = null)
        {
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                wbRequest.Method = "GET";
                wbRequest.Headers.Add("Authorization", httpToken);
                
                if (IfModifiedSince != null && IfModifiedSince != default(DateTime))
                {
                    wbRequest.IfModifiedSince = IfModifiedSince;
                }
                if (headers != null)
                {
                    foreach (var item in headers)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sReader = new StreamReader(responseStream))
                    {
                        return sReader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                message = ex.Message + ",堆栈信息:" + ex.StackTrace;
                return string.Empty;
            }            
        }
    }

  

2、如果是https需要判断,将https请求服务器证书为ture并设置安全协议类型

ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

  

 

【C#】Http帮助类

标签:trace   https   api   error   nbsp   json   concat   method   方式   

原文地址:https://www.cnblogs.com/Seven77yixuan/p/10915404.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!