c# http请求封装

看到别人写的代码copy一下,作为备份。

/// <summary>
    /// Restful客户端
    /// </summary>
    public class RESTClient
    {

        // 常量
        private const string HEAD_KEY = "Authorization";
        private const string TOKEN_KEY_PREFIX = "SmartTracking";

        // Restful访问基地址
        private string baseUrl = string.Empty;

        /// <summary>
        /// Restful访问基地址
        /// </summary>
        public string BaseUrl
        {
            get { return baseUrl; }
            set { baseUrl = value; }
        }

        // 令牌钥匙
        private string tokenKey = string.Empty;

        /// <summary>
        /// 令牌钥匙
        /// </summary>
        public string TokenKey
        {
            set { tokenKey = value; }
        }

        // 访问超时时间
        private long timeout;

        /// <summary>
        /// 访问超时时间
        /// </summary>
        public long Timeout
        {
            get { return timeout; }
            set { timeout = value; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public RESTClient()
        {

        }

        /// <summary>
        /// 请求GET方法
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public RESTResponseEntity RequestGet(string url)
        {
            RESTResponseEntity entity = new RESTResponseEntity();
            try
            {
                HttpClient httpClient = new HttpClient();
                if(timeout > 0){
                    httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
                }
                httpClient.DefaultRequestHeaders.Add(HEAD_KEY, TOKEN_KEY_PREFIX + " " + tokenKey);
                string strUrl = baseUrl + url;
                HttpResponseMessage hrm = httpClient.GetAsync(strUrl).Result;
                entity.StatusCode = Convert.ToInt32(hrm.StatusCode);
                entity.Buffer = hrm.Content.ReadAsByteArrayAsync().Result;
            }
            catch (Exception ex)
            {
                Log.WriteLogFile(ex, "RESTClient RequestGet() Error");
            }
            return entity;
        }

        /// <summary>
        /// 请求POST方法
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public RESTResponseEntity RequestPOST(string url,List<KeyValuePair<string, string>> paras)
        {
            RESTResponseEntity entity = new RESTResponseEntity();
            HttpClient httpClient = null;
            FormUrlEncodedContent content = null;
            HttpResponseMessage hrm = null;
            try
            {
                httpClient = new HttpClient();
                if (timeout > 0)
                {
                    httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
                }
                httpClient.DefaultRequestHeaders.Add(HEAD_KEY, TOKEN_KEY_PREFIX + " "+ tokenKey);
                content = new FormUrlEncodedContent(paras);
                string strUrl = baseUrl + url;
                hrm = httpClient.PostAsync(strUrl, content).Result;
                entity.StatusCode = Convert.ToInt32(hrm.StatusCode);
                entity.Buffer = hrm.Content.ReadAsByteArrayAsync().Result;
                httpClient.Dispose();
            }
            catch (Exception ex)
            {
                Log.WriteLogFile(ex, "RESTClient RequestPOST() Error");
                //Console.WriteLine("RESTClient RequestPOST():" + ex.Message);
            }
            if (httpClient != null)
            {
                httpClient.Dispose();
                httpClient = null;
            }
            if (content != null)
            {
                content.Dispose();
                content = null;
            }
            if (hrm != null)
            {
                hrm.Dispose();
                hrm = null;
            }
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            return entity;
        }
        /// <summary>
        /// 请求POST方法
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public RESTResponseEntity RequestMulPOST(string url, List<KeyValuePair<string, string>> paras)
        {
            RESTResponseEntity entity = new RESTResponseEntity();
            HttpClient httpClient = null;
            FormUrlEncodedContent content = null;
            MultipartFormDataContent mulcontnt = null;
            HttpResponseMessage hrm = null;
            try
            {
                httpClient = new HttpClient();
                if (timeout > 0)
                {
                    httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
                }
                httpClient.DefaultRequestHeaders.Add(HEAD_KEY, TOKEN_KEY_PREFIX + " " + tokenKey);
                content = new FormUrlEncodedContent(paras);
                mulcontnt = new MultipartFormDataContent();
                string strUrl = baseUrl + url;
                hrm = httpClient.PostAsync(strUrl, content).Result;
                entity.StatusCode = Convert.ToInt32(hrm.StatusCode);
                entity.Buffer = hrm.Content.ReadAsByteArrayAsync().Result;
                httpClient.Dispose();
            }
            catch (Exception ex)
            {
                Log.WriteLogFile(ex, "RESTClient RequestPOST() Error");
                //Console.WriteLine("RESTClient RequestPOST():" + ex.Message);
            }
            if (httpClient != null)
            {
                httpClient.Dispose();
                httpClient = null;
            }
            if (content != null)
            {
                content.Dispose();
                content = null;
            }
            if (hrm != null)
            {
                hrm.Dispose();
                hrm = null;
            }
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            return entity;
        }

        /// <summary>
        /// 请求PUT方法
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public RESTResponseEntity RequestPUT(string url, List<KeyValuePair<string, string>> paras)
        {
            RESTResponseEntity entity = new RESTResponseEntity();
            try
            {
                HttpClient httpClient = new HttpClient();
                if (timeout > 0)
                {
                    httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
                }
                httpClient.DefaultRequestHeaders.Add(HEAD_KEY, TOKEN_KEY_PREFIX + " " + tokenKey);
                FormUrlEncodedContent content = new FormUrlEncodedContent(paras);
                string strUrl = baseUrl + url;
                HttpResponseMessage hrm = httpClient.PutAsync(strUrl, content).Result;
                entity.StatusCode = Convert.ToInt32(hrm.StatusCode);
                entity.Buffer = hrm.Content.ReadAsByteArrayAsync().Result;
            }
            catch (Exception ex)
            {
                Log.WriteLogFile(ex, "RESTClient RequestPUT() Error");
            }
            return entity;
        }

        /// <summary>
        /// 请求DELETE方法
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public RESTResponseEntity RequestDELETE(string url)
        {
            RESTResponseEntity entity = new RESTResponseEntity();
            try
            {
                HttpClient httpClient = new HttpClient();
                if (timeout > 0)
                {
                    httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
                }
                httpClient.DefaultRequestHeaders.Add(HEAD_KEY, TOKEN_KEY_PREFIX + " " + tokenKey);
                string strUrl = baseUrl + url;
                HttpResponseMessage hrm = httpClient.DeleteAsync(strUrl).Result;
                entity.StatusCode = Convert.ToInt32(hrm.StatusCode);
                entity.Buffer = hrm.Content.ReadAsByteArrayAsync().Result;
            }
            catch (Exception ex)
            {
                Log.WriteLogFile(ex, "RESTClient RequestDELETE() Error");
            }
            return entity;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值