C#关于HttpClient的统一配置

Posted

tags:

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

    public class BaseHttpClient
    {
        protected string contentType;

        public BaseHttpClient()
        {
            this.contentType = "application/json";
        }

        protected const int RESPONSE_OK = 200;
        //设置读取超时时间
        private const int DEFAULT_SOCKET_TIMEOUT = (30 * 1000); // milliseconds

        /// <summary>
        /// HTTP 验证
        /// </summary>
        /// <returns></returns>
        public virtual Dictionary<string, string> Authorization()
        {
            return null;
        }

        /// <summary>
        /// 构建请求参数
        /// </summary>
        /// <param name="dicList"></param>
        /// <returns></returns>
        public String BuildQueryStr(Dictionary<String, String> dicList)
        {
            String postStr = dicList.Aggregate("", (current, item) => current + item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&");

            postStr = postStr.Substring(0, postStr.LastIndexOf(&));
            return postStr;
        }

        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="method">请求方式</param>
        /// <param name="url">请求链接</param>
        /// <param name="reqParams">请求参数</param>
        /// <returns></returns>
        public ResultDTO SendRequest(Method method, String url, String reqParams)
        {
            HttpWebRequest myReq = null;
            HttpWebResponse response = null;
            try
            {
                if (method == Method.Get||method==Method.Delete)
                {
                    url += "?" + reqParams;
                }
                myReq = (HttpWebRequest) WebRequest.Create(url);
                myReq.Method = method.ToString();
                myReq.ReadWriteTimeout = DEFAULT_SOCKET_TIMEOUT;
                myReq.ContentType = contentType;

                //权限验证
                var auth = this.Authorization();
                if (auth != null)
                {
                    foreach (var item in auth)
                    {
                        myReq.Headers.Add(item.Key, item.Value);
                    }
                }

                if (myReq.Method == "POST" || myReq.Method == "Put")
                {
                    byte[] bs = Encoding.UTF8.GetBytes(reqParams);
                    myReq.ContentLength = bs.Length;
                    using (Stream reqStream = myReq.GetRequestStream())
                    {
                        reqStream.Write(bs, 0, bs.Length);
                        reqStream.Close();
                    }
                }
                response = (HttpWebResponse) myReq.GetResponse();
                if (Equals(response.StatusCode, HttpStatusCode.OK) ||
                    Equals(response.StatusCode, HttpStatusCode.Created))
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        return WebApi.Success(reader.ReadToEnd());
                    }
                }
                return WebApi.Error("");
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    //HttpStatusCode errorCode = ((HttpWebResponse) e.Response).StatusCode;
                    //string statusDescription = ((HttpWebResponse)e.Response).StatusDescription;
                    using (StreamReader sr = new StreamReader(((HttpWebResponse) e.Response).GetResponseStream(),
                            Encoding.UTF8))
                    {
                        return WebApi.Error(sr.ReadToEnd());
                    }
                }
                return WebApi.Error(e.Message);
            }
            //这里不再抓取非http的异常,如果异常抛出交给开发者自行处理
            //catch (System.Exception ex)
            //{
            //     String errorMsg = ex.Message;
            //     Debug.Print(errorMsg);
            //}
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                if (myReq != null)
                {
                    myReq.Abort();
                }
            }
        }
    }

    //请求方式
    public enum Method
    {
        Post,
        Delete,
        Get,
        Put
    }

 

以上是关于C#关于HttpClient的统一配置的主要内容,如果未能解决你的问题,请参考以下文章

C#关于HttpClient的应用:融云IM集成

C#关于HttpClient的应用:极光推送IM集成

C#关于HttpClient的应用:获取IP所在的地理位置信息

C#用HttpClient类post get,怎么设置cookies

如何为 XSLT 代码片段配置 CruiseControl 的 C# 版本?

C# 获得目录创建时间的源码片段