• HttpClient封装


    public enum HttpMethod { Get, Post }
    
    
        /// <summary>HttpClient</summary>   
        public class HttpClient
        {
            public Encoding encoding { get; set; }
    
            public HttpClient()
            {
                this.encoding = Encoding.Default;
            }
            public HttpClient(Encoding encoding)
            {
                this.encoding = encoding;
            }
    
            /// <summary>
            /// Get请求
            /// </summary>
            public HttpResponse get(string url, HttpParameter[] parameters = null, Dictionary<string, string> headers = null)
            {
                return this.request(url, HttpMethod.Get, parameters, headers);
            }
    
            /// <summary>
            /// Post请
            /// </summary>
            public HttpResponse post(string url, HttpParameter[] parameters = null, Dictionary<string, string> headers = null, string postData = null)
            {
                return this.request(url, HttpMethod.Post, parameters, headers, postData);
            }
    
            /// <summary>
            /// 请求
            /// </summary>
            public HttpResponse request(string url, HttpMethod method = HttpMethod.Get, HttpParameter[] parameters = null, Dictionary<string, string> headers = null, string postData = null, string contentType = null)
            {
                if (method == HttpMethod.Get && parameters != null)
                    url += (url.IndexOf("?") == -1 ? "?" : "&") + this.buildStringParameters(parameters);
    
                HttpWebRequest http = WebRequest.Create(url) as HttpWebRequest;
                http.ServicePoint.Expect100Continue = false;
                http.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
    
                if (headers != null)
                {
                    foreach (var key in headers.Keys)
                    {
                        http.Headers[key] = headers[key];
                    }
                }
    
                switch (method)
                {
                    case HttpMethod.Get:
                        {
                            http.Method = "GET";
                            break;
                        }
                    case HttpMethod.Post:
                        {
                            http.Method = "POST";
                            if (!string.IsNullOrEmpty(contentType))
                            {
                                http.ContentType = contentType;
                                using (StreamWriter request = new StreamWriter(http.GetRequestStream()))
                                {
                                    try
                                    {
                                        if (postData == null)
                                            request.Write(this.buildStringParameters(parameters));
                                        else
                                            request.Write(postData);
                                    }
                                    finally
                                    {
                                        request.Close();
                                    }
                                }
                            }
                            else
                            {
                                if (parameters != null && parameters.Count(p => p.isBinary) > 0)
                                {
                                    string boundary = this.getBoundary();
                                    http.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                                    http.AllowWriteStreamBuffering = true;
                                    using (Stream request = http.GetRequestStream())
                                    {
                                        try
                                        {
                                            var raw = this.buildBinaryParameters(boundary, parameters);
                                            request.Write(raw, 0, raw.Length);
                                        }
                                        finally
                                        {
                                            request.Close();
                                        }
                                    }
                                }
                                else
                                {
                                    http.ContentType = "application/x-www-form-urlencoded";
    
                                    using (StreamWriter request = new StreamWriter(http.GetRequestStream()))
                                    {
                                        try
                                        {
                                            if (postData == null)
                                                request.Write(this.buildStringParameters(parameters));
                                            else
                                                request.Write(postData);
                                        }
                                        finally
                                        {
                                            request.Close();
                                        }
                                    }
                                }
                            }
                            break;
                        }
                }
    
    
                var httpResponse = new HttpResponse();
                try
                {
                    using (WebResponse response = http.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream(), this.encoding))
                        {
                            httpResponse.content = reader.ReadToEnd().Trim();
                            reader.Close();
                        }
                        response.Close();
                    }
                }
                catch (WebException e)
                {
                    httpResponse.status = e.Status;
                    httpResponse.Message = e.Message;
                    httpResponse.StackTrace = e.StackTrace;
                    httpResponse.TotalMessage=e.Status+"======"+ e.Message+"=====" + e.StackTrace;
                }
    
                return httpResponse;
            }
    
            /// <summary>
            /// hash值
            /// </summary>
            private string getBoundary()
            {
                string pattern = "abcdefghijklmnopqrstuvwxyz0123456789";
                StringBuilder boundaryBuilder = new StringBuilder();
                Random rnd = new Random();
                for (int i = 0; i < 10; i++)
                {
                    var index = rnd.Next(pattern.Length);
                    boundaryBuilder.Append(pattern[index]);
                }
                return boundaryBuilder.ToString();
            }
    
            /// <summary>
            /// 生成字符参数
            /// </summary>
            private string buildStringParameters(HttpParameter[] parameters)
            {
                if (parameters == null) return "";
    
                var s = new StringBuilder("");
                bool first = true;
                foreach (var item in parameters)
                {
                    if (first) first = false;
                    else s.Append("&");
    
                    var value = string.Format("{0}", item.value);
                    s.Append(Uri.EscapeDataString(item.name)).Append("=").Append(Uri.EscapeDataString(value));
                }
                return s.ToString();
            }
    
            /// <summary>
            /// 生成二进制参数
            /// </summary>
            /// <param name="boundary"></param>
            /// <param name="parameters">参数</param>
            /// <returns></returns>
            private byte[] buildBinaryParameters(string boundary, params HttpParameter[] parameters)
            {
                List<HttpParameter> pairs = new List<HttpParameter>(parameters);
                MemoryStream buff = new MemoryStream();
    
                byte[] headerBuff = Encoding.ASCII.GetBytes(string.Format("
    --{0}
    ", boundary));
                byte[] footerBuff = Encoding.ASCII.GetBytes(string.Format("
    --{0}--", boundary));
    
                StringBuilder contentBuilder = new StringBuilder();
    
                foreach (HttpParameter p in pairs)
                {
                    if (!p.isBinary)
                    {
                        var value = string.Format("{0}", p.value);
                        if (string.IsNullOrEmpty(value))
                        {
                            continue;
                        }
    
    
                        buff.Write(headerBuff, 0, headerBuff.Length);
                        byte[] dispositonBuff = Encoding.UTF8.GetBytes(string.Format("content-disposition: form-data; name="{0}"
    
    {1}", p.name, p.value.ToString()));
                        buff.Write(dispositonBuff, 0, dispositonBuff.Length);
    
                    }
                    else
                    {
                        buff.Write(headerBuff, 0, headerBuff.Length);
                        string headerTemplate = "Content-Disposition: form-data; name="{0}"; filename="{1}"
    Content-Type: "image/unknow"
    Content-Transfer-Encoding: binary
    
    ";
                        byte[] fileBuff = System.Text.Encoding.UTF8.GetBytes(string.Format(headerTemplate, p.name, string.Format("upload{0}", BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0))));
                        buff.Write(fileBuff, 0, fileBuff.Length);
                        byte[] file = (byte[])p.value;
                        buff.Write(file, 0, file.Length);
    
                    }
                }
    
                buff.Write(footerBuff, 0, footerBuff.Length);
                buff.Position = 0;
    
                byte[] contentBuff = new byte[buff.Length];
                buff.Read(contentBuff, 0, contentBuff.Length);
                buff.Close();
                buff.Dispose();
                return contentBuff;
            }
        }
  • 相关阅读:
    Python之面向对象新式类和经典类
    Python之面向对象继承和派生
    Python之面向对象类和对象
    Python之面向对象的程序设计
    Python之面向对象函数式编程
    Python之内置函数
    列表解析与生成器表达式
    03: 交换机基本原理与配置
    02: 网络布线与数制转换
    01:数据封装解封的过程
  • 原文地址:https://www.cnblogs.com/jameslif/p/6898578.html
Copyright © 2020-2023  润新知