• 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
        }
  • 相关阅读:
    mysql练习
    导航 开发 常用 官方网址 办公 政府 网站 url
    Yii 数据库 连接 Error Info: 向一个无法连接的网络尝试了一个套接字操作。
    xampp Apache Access forbidden! Error 403 解决方法
    MySQL 没有密码 初始化 设置 用户名
    Apache 虚拟机 vhosts C:WINDOWSsystem32driversetchosts
    js 返回上一页 链接 按钮
    MySQL concat concat_ws group_concat 函数(连接字符串)
    PHP的UTF-8中文转拼音处理类(性能已优化至极致)
    原生JavaScript实现金额大写转换函数
  • 原文地址:https://www.cnblogs.com/xuhang/p/5204964.html
Copyright © 2020-2023  润新知