C#Http帮助类

Posted seven77yixuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#Http帮助类相关的知识,希望对你有一定的参考价值。

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帮助类的主要内容,如果未能解决你的问题,请参考以下文章

csharp C#代码片段 - 使类成为Singleton模式。 (C#4.0+)https://heiswayi.github.io/2016/simple-singleton-pattern-us

C#Http帮助类

在内部片段类中使用ListView

csharp c#HTTP请求帮助类

片段 null 必须是公共静态类才能从实例状态正确重新创建

调用模板化成员函数:帮助我理解另一个 *** 帖子中的代码片段