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

C#关于HttpClient的统一配置(一)

时间:2016-02-21 15:34:29      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

    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的统一配置(一)

标签:

原文地址:http://www.cnblogs.com/xuhang/p/5204964.html

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