• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
    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
    }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#Mid窗口的创建发布时间:2022-07-13
下一篇:
C#笔记(二)——输入输出函数发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap