[C.C++] C#实现HTTP访问类HttpHelper的示例详解

2192 0
Honkers 2022-11-9 09:37:49 | 显示全部楼层 |阅读模式
在项目开发过程中,我们经常会访问第三方接口,如我们需要接入的第三方接口是Web API,这时候我们就需要使用HttpHelper调用远程接口了。示例中的HttpHelper类使用Log4Net记录了每次调用的请求内容和响应内容的日志,并且每条日志都带上了链路ID和标识,这样方便我们在排查问题时能快速的找到当时的请求和响应内容,进而定位分析问题。大家在使用的时候如不需要记录日志,删除掉即可。
HttpHelper类代码如下:
  1. public class HttpHelper : IDisposable
  2.     {
  3.         private bool _disposable = false;
  4.         /// <summary>
  5.         /// 请求编码格式默认utf-8;
  6.         /// </summary>
  7.         public Encoding HtmlEncoding = Encoding.UTF8;
  8.         /// <summary>
  9.         /// 请求时间
  10.         /// </summary>
  11.         public int Timeout = 5000;
  12.         public CookieContainer Cookies = null;
  13.         /// <summary>
  14.         /// 是否记录Cookies
  15.         /// </summary>
  16.         public bool IsRecordCookie = false;
  17.         public string ContentType = "application/x-www-form-urlencoded";
  18.         public string AcceptLanguage = "en-US, en; q=0.8, zh-Hans-CN; q=0.5, zh-Hans; q=0.3";
  19.         public string KeepAlive = "Keep-Alive";
  20.         public string Accept = "*/*";
  21.         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/53.36 Edge/12.10240";
  22.         private static ILogger Logger = Log4NetLoggerFactory.Instance.Create("remote.info");
  23.         public HttpHelper()
  24.         {
  25.             //允许最大连接数,突破Http协议的并发连接数限制
  26.             ServicePointManager.DefaultConnectionLimit = 512;
  27.         }
  28.         /// <summary>
  29.         /// 上传图片
  30.         /// </summary>
  31.         /// <param name="url"></param>
  32.         /// <param name="bArr"></param>
  33.         /// <param name="fileName"></param>
  34.         /// <returns></returns>
  35.         public HttpRequestEntity RequestFile(string url, byte[] bArr, string fileName = "")
  36.         {
  37.             var result = new HttpRequestEntity { IsSuccess = 0 };
  38.             //后续需要再放开,启用时需增加日志收集
  39.             //if (string.IsNullOrEmpty(url))
  40.             //    throw new ArgumentNullException("请求Url不能为空值");
  41.             //if (bArr == null || bArr.Length <= 0)
  42.             //    throw new AccessViolationException("缺少输入数据");
  43.             //Stream requestStream = null;
  44.             //StreamReader streamReader = null;
  45.             //HttpWebResponse response = null;
  46.             //HttpWebRequest request = null;
  47.             //try
  48.             //{
  49.             //    request = WebRequest.Create(url) as HttpWebRequest;
  50.             //    request.AllowAutoRedirect = true;
  51.             //    request.Method = "POST";
  52.             //    string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
  53.             //    request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
  54.             //    byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
  55.             //    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
  56.             //    if (string.IsNullOrEmpty(fileName))
  57.             //        fileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  58.             //    //请求头部信息
  59.             //    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));
  60.             //    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
  61.             //    request.Headers.Add("auth", fileName);
  62.             //    Stream postStream = request.GetRequestStream();
  63.             //    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
  64.             //    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  65.             //    postStream.Write(bArr, 0, bArr.Length);
  66.             //    postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  67.             //    postStream.Close();
  68.             //    response = request.GetResponse() as HttpWebResponse;
  69.             //    requestStream = response.GetResponseStream();
  70.             //    if (response.StatusCode == HttpStatusCode.OK)
  71.             //    {
  72.             //        result.IsSuccess = 0;
  73.             //        if (requestStream != null)
  74.             //        {
  75.             //            streamReader = new StreamReader(requestStream, HtmlEncoding);
  76.             //            result.ResponseContent = streamReader.ReadToEnd();
  77.             //        }
  78.             //    }
  79.             //}
  80.             //catch (Exception ex)
  81.             //{
  82.             //    result.IsSuccess = 1;
  83.             //    result.ResponseContent = ex.Message;
  84.             //}
  85.             //finally
  86.             //{
  87.             //    if (requestStream != null)
  88.             //    {
  89.             //        requestStream.Close();
  90.             //        requestStream.Dispose();
  91.             //    }
  92.             //    if (streamReader != null)
  93.             //    {
  94.             //        streamReader.Close();
  95.             //        streamReader.Dispose();
  96.             //    }
  97.             //    request.Abort();
  98.             //    if (response != null)
  99.             //        response.Close();
  100.             //}
  101.             return result;
  102.         }
  103.         /// <summary>
  104.         /// 基本请求方法
  105.         /// </summary>
  106.         /// <param name="requestType">HTTP请求类型</param>
  107.         /// <param name="url">请求的URL</param>
  108.         /// <param name="requestData">请求参数</param>
  109.                 /// <param name="traceID">链路ID,方便查询日志</param>
  110.                 /// <param name="markType">请求标识,方便查询日志</param>
  111.         /// <returns></returns>
  112.         private HttpRequestEntity BaseRequest(RequestType requestType, string url, string requestData, string traceID,string markType)
  113.         {
  114.             var result = new HttpRequestEntity { IsSuccess = 0 };
  115.             if (string.IsNullOrEmpty(url))
  116.                 throw new ArgumentNullException("请求Url不能为空值");
  117.             Stopwatch stopwatch = new Stopwatch();
  118.             stopwatch.Start();
  119.             Dictionary<string, object> resultLog = new Dictionary<string, object>();//log对象
  120.             resultLog.Add("logType", "remote");
  121.             resultLog.Add("traceID", traceID);
  122.             resultLog.Add("localIp", IpHelper.LocalIp);
  123.             resultLog.Add("markType", markType);
  124.             resultLog.Add("url", url);            
  125.             resultLog.Add("requestContent", HttpUtility.UrlDecode(requestData, Encoding.UTF8));
  126.             resultLog.Add("createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
  127.             StackTrace ss = new StackTrace(true);
  128.             System.Reflection.MethodBase mb = ss.GetFrame(2).GetMethod();//0表示当前栈空间,1表示上一级的栈空间,依次类推
  129.             resultLog.Add("className", mb.DeclaringType.FullName);
  130.             resultLog.Add("methodName", mb.Name);
  131.             HttpStatusCode statusCode = HttpStatusCode.OK;
  132.             if (IsRecordCookie)
  133.                 Cookies = new CookieContainer();
  134.             Stream requestStream = null;
  135.             StreamReader streamReader = null;
  136.             HttpWebRequest webRe = null;
  137.             HttpWebResponse webPos = null;
  138.             try
  139.             {
  140.                 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  141.                 {
  142.                     ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  143.                     webRe = WebRequest.Create(url) as HttpWebRequest;
  144.                     webRe.ProtocolVersion = HttpVersion.Version10;
  145.                 }
  146.                 else
  147.                 {
  148.                     webRe = (HttpWebRequest)WebRequest.Create(url);
  149.                 }
  150.                 webRe.Headers.Add("Accept-Language", AcceptLanguage);
  151.                 webRe.Headers.Add("Keep-Alive", KeepAlive);
  152.                 webRe.UserAgent = UserAgent;
  153.                 webRe.Accept = Accept;
  154.                 webRe.Timeout = Timeout;
  155.                 webRe.ReadWriteTimeout = Timeout;
  156.                 webRe.CookieContainer = Cookies;
  157.                 if (requestType == RequestType.Post)
  158.                 {
  159.                     webRe.ContentType = string.Format("{0}; {1}", ContentType, HtmlEncoding.BodyName);
  160.                     byte[] datas = HtmlEncoding.GetBytes(requestData);
  161.                     webRe.Method = "POST";
  162.                     webRe.ContentLength = datas.Length;
  163.                     webRe.MaximumResponseHeadersLength = -1;
  164.                     requestStream = webRe.GetRequestStream();
  165.                     requestStream.Write(datas, 0, datas.Length);
  166.                     requestStream.Flush();
  167.                     requestStream.Close();
  168.                 }
  169.                 else
  170.                     webRe.Method = "GET";
  171.                 webPos = (HttpWebResponse)webRe.GetResponse();
  172.                 resultLog.Add("requestType", webRe.Method);
  173.                 statusCode = webPos.StatusCode;
  174.                 result.ResponseLength = webPos.ContentLength;
  175.                 result.ResponseEncodingName = webPos.ContentEncoding;
  176.                 requestStream = webPos.GetResponseStream();
  177.                 if (webPos.StatusCode == HttpStatusCode.OK)
  178.                 {
  179.                     result.IsSuccess = 0;
  180.                     if (requestStream != null)
  181.                     {
  182.                         streamReader = new StreamReader(requestStream, HtmlEncoding);
  183.                         result.ResponseContent = streamReader.ReadToEnd();
  184.                     }
  185.                 }
  186.             }
  187.             catch (Exception ex)
  188.             {
  189.                 result.IsSuccess = 1;
  190.                 result.ResponseContent = ex.Message;
  191.             }
  192.             finally
  193.             {
  194.                 if (requestStream != null)
  195.                 {
  196.                     requestStream.Close();
  197.                     requestStream.Dispose();
  198.                 }
  199.                 if (streamReader != null)
  200.                 {
  201.                     streamReader.Close();
  202.                     streamReader.Dispose();
  203.                 }
  204.                 webRe.Abort();
  205.                 if (webPos != null)
  206.                     webPos.Close();
  207.             }
  208.             if (result.IsSuccess == 1)
  209.             {
  210.                 resultLog.Add("status", HttpStatusCode.InternalServerError);
  211.                 resultLog.Add("success", false);
  212.                 resultLog.Add("responseContent", result.ResponseContent);
  213.                 stopwatch.Stop();
  214.                 resultLog.Add("elapseTime", stopwatch.Elapsed.TotalMilliseconds);
  215.                 string log = JsonConvert.SerializeObject(resultLog);
  216.                 Logger.Info(log);
  217.                 Logger.Error(log);
  218.             }
  219.             else
  220.             {
  221.                 resultLog.Add("status", statusCode);
  222.                 resultLog.Add("success", true);
  223.                 resultLog.Add("responseContent", result.ResponseContent);
  224.                 stopwatch.Stop();
  225.                 resultLog.Add("elapseTime", stopwatch.Elapsed.TotalMilliseconds);
  226.                 string log = JsonConvert.SerializeObject(resultLog);
  227.                 Logger.Info(log);
  228.             }
  229.             return result;
  230.         }
  231.         private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  232.         {
  233.             return true; //总是接受  
  234.         }
  235.         /// <summary>
  236.         /// Get请求
  237.         /// </summary>
  238.         /// <param name="url">请求地址</param>
  239.                 /// <param name="traceID">链路ID,方便查询日志</param>
  240.                 /// <param name="markType">请求标识,方便查询日志</param>
  241.         /// <returns></returns>
  242.         public HttpRequestEntity Request(string url, string traceID, string markType)
  243.         {
  244.             return BaseRequest(RequestType.Get, url, string.Empty, traceID, markType);
  245.         }
  246.         /// <summary>
  247.         /// Post请求
  248.         /// </summary>
  249.         /// <param name="url">请求地址Url</param>
  250.         /// <param name="requestData">请求内容参数</param>
  251.                 /// <param name="traceID">链路ID,方便查询日志</param>
  252.                 /// <param name="markType">请求标识,方便查询日志</param>
  253.         /// <returns></returns>
  254.         public HttpRequestEntity Request(string url, string requestData, string traceID, string markType)
  255.         {
  256.             return BaseRequest(RequestType.Post, url, requestData, traceID, markType);
  257.         }
  258.         ~HttpHelper()
  259.         {
  260.             Dispose(false);
  261.         }
  262.         #region IDisposable 成员
  263.         public void Dispose()
  264.         {
  265.             Dispose(true);
  266.             GC.SuppressFinalize(this);
  267.         }
  268.         protected virtual void Dispose(bool disposing)
  269.         {
  270.             if (this._disposable)
  271.                 return;
  272.             if (disposing)
  273.             {
  274.             }
  275.             _disposable = true;
  276.         }
  277.         #endregion
  278.     }
  279.     /// <summary>
  280.     /// HttpHelper请求方式
  281.     /// </summary>
  282.     public enum RequestType
  283.     {
  284.         /// <summary>
  285.         /// Get请求
  286.         /// </summary>
  287.         Get,
  288.         /// <summary>
  289.         /// Post请求
  290.         /// </summary>
  291.         Post
  292.     }
  293.     /// <summary>
  294.     /// HttpHelper请求时返回实体
  295.     /// </summary>
  296.     public class HttpRequestEntity
  297.     {
  298.         /// <summary>
  299.         /// 请求是否成功 0-成功(返回Http状态码200) 1-失败(出现异常)
  300.         /// </summary>
  301.         public int IsSuccess { get; set; }
  302.         /// <summary>
  303.         /// 请求返回内容
  304.         /// </summary>
  305.         public string ResponseContent { get; set; }
  306.         /// <summary>
  307.         /// 请求返回内容长度
  308.         /// </summary>
  309.         public long ResponseLength { get; set; }
  310.         /// <summary>
  311.         /// 请求返回编码类型
  312.         /// </summary>
  313.         public string ResponseEncodingName { get; set; }
  314.     }
复制代码
调用示例如下:
  1. HttpHelper helper = new HttpHelper();
  2. HttpRequestEntity response = helper.Request("需要访问的URL", "请求需要的参数", "访问链路ID", "访问标识");
  3. if (response.IsSuccess != 0)
  4. {
  5.         //程序处理异常,请重试!
  6. }
  7. else
  8. {
  9.         //请求响应成功       
  10. }
复制代码
到此这篇关于C#实现HTTP访问类HttpHelper的示例详解的文章就介绍到这了,更多相关C# HTTP访问类HttpHelper内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

荣誉红客

关注
  • 4004
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行