C#实现HTTP访问类HttpHelper的示例详解

在项目开发过程中,我们经常会访问第三方接口,如我们需要接入的第三方接口是WebAPI,这时候我们就需要使用HttpHelper调用远程接口了。本文为大家介绍了C#实现HTTP访问类HttpHelper的示例代码,需要的可以参考一下

在项目开发过程中,我们经常会访问第三方接口,如我们需要接入的第三方接口是Web API,这时候我们就需要使用HttpHelper调用远程接口了。示例中的HttpHelper类使用Log4Net记录了每次调用的请求内容和响应内容的日志,并且每条日志都带上了链路ID和标识,这样方便我们在排查问题时能快速的找到当时的请求和响应内容,进而定位分析问题。大家在使用的时候如不需要记录日志,删除掉即可。

HttpHelper类代码如下:

 public class HttpHelper : IDisposable
    {
        private bool _disposable = false;
        /// <summary>
        /// 请求编码格式默认utf-8;
        /// </summary>
        public Encoding HtmlEncoding = Encoding.UTF8;
        /// <summary>
        /// 请求时间
        /// </summary>
        public int Timeout = 5000;
 
        public CookieContainer Cookies = null;
        /// <summary>
        /// 是否记录Cookies
        /// </summary>
        public bool IsRecordCookie = false;
 
        public string ContentType = "application/x-www-form-urlencoded";
 
        public string AcceptLanguage = "en-US, en; q=0.8, zh-Hans-CN; q=0.5, zh-Hans; q=0.3";
 
        public string KeepAlive = "Keep-Alive";
 
        public string Accept = "*/*";
 
        private const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240";
 
        private static ILogger Logger = Log4NetLoggerFactory.Instance.Create("remote.info");
 
        public HttpHelper()
        {
            //允许最大连接数,突破Http协议的并发连接数限制
            ServicePointManager.DefaultConnectionLimit = 512;
        }
 
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="bArr"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public HttpRequestEntity RequestFile(string url, byte[] bArr, string fileName = "")
        {
            var result = new HttpRequestEntity { IsSuccess = 0 };
            //后续需要再放开,启用时需增加日志收集
            //if (string.IsNullOrEmpty(url))
            //    throw new ArgumentNullException("请求Url不能为空值");
 
            //if (bArr == null || bArr.Length <= 0)
            //    throw new AccessViolationException("缺少输入数据");
 
            //Stream requestStream = null;
            //StreamReader streamReader = null;
            //HttpWebResponse response = null;
            //HttpWebRequest request = null;
            //try
            //{
            //    request = WebRequest.Create(url) as HttpWebRequest;
            //    request.AllowAutoRedirect = true;
            //    request.Method = "POST";
            //    string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            //    request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            //    byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            //    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
 
            //    if (string.IsNullOrEmpty(fileName))
            //        fileName = DateTime.Now.ToString("yyyyMMddHHmmss");
 
            //    //请求头部信息 
            //    StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
            //    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
            //    request.Headers.Add("auth", fileName);
            //    Stream postStream = request.GetRequestStream();
            //    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            //    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            //    postStream.Write(bArr, 0, bArr.Length);
            //    postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            //    postStream.Close();
            //    response = request.GetResponse() as HttpWebResponse;
            //    requestStream = response.GetResponseStream();
            //    if (response.StatusCode == HttpStatusCode.OK)
            //    {
            //        result.IsSuccess = 0;
            //        if (requestStream != null)
            //        {
            //            streamReader = new StreamReader(requestStream, HtmlEncoding);
            //            result.ResponseContent = streamReader.ReadToEnd();
            //        }
            //    }
            /

本文标题为:C#实现HTTP访问类HttpHelper的示例详解

基础教程推荐