zoukankan      html  css  js  c++  java
  • 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
        }
  • 相关阅读:
    JetBrains全家桶破解-Golang-Pycharm-IDEA等-不分平台
    k8s node update kernel
    k8s 图解
    k8s孤儿卷的问题
    k8s相关工作中常用命令
    AMQ死信引发宕机的问题
    StackStorm简介之actions
    DRF 使用入门
    python装饰器的简单实用
    type和object的关系
  • 原文地址:https://www.cnblogs.com/xuhang/p/5204964.html
Copyright © 2011-2022 走看看