首页 / 算法 / 【原创-算法-实现】异步HTTP请求操作
【原创-算法-实现】异步HTTP请求操作
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【原创-算法-实现】异步HTTP请求操作,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4599字,纯文字阅读大概需要7分钟。
内容图文
![【原创-算法-实现】异步HTTP请求操作](/upload/InfoBanner/zyjiaocheng/1178/6f09110f898e41a3875c77c456cd71ff.jpg)
一、说明
1) 这个类 是我 在真实项目中,优化解决真实问题 时,不参考第三方代码,完全由自己查阅MSDN官方文档 , 完成的一个真实生产环境中使用的功能类
2) 读者在使用此类时,请尊重原创,在代码中加上原创注释:// Author -- Meng.NET (cnblogs.com) ,同时欢迎 二次改进、二次创作 以共同进步
3) 此代码以【面向对象】、【C#闭包】、【异步回调】、【超时】、【等待】、【自动重试】方式实现及完成,且可以配置扩展
二、代码
废话不多说,上干货,代码如下:
![技术分享](/upload/getfiles/default/2022/11/9/20221109024939739.jpg)
![技术分享](/upload/getfiles/default/2022/11/9/20221109024939760.jpg)
1 /// <summary> 2 /// 异步 Http 3 /// </summary> 4 public class Remoter 5 { 6 /* 7 * LM,2016/08/18 8 * C#闭包化,异步化,Web操作 9 * 以便支持POS多接口多操作同时使用 10 */ 11 12 /// <summary> 13 /// 请求地址 14 /// </summary> 15 public string URL { get; set; } 16 17///<summary> 18/// 请求方式 19///</summary> 20publicstring RequestMethod { get; set; } 21 22///<summary> 23/// 请求数据 24///</summary> 25publicstring JsonContent { get; set; } 26 27// 28privatebyte[] Buffer { get; set; } 29private Stream RequestStream { get; set; } 30private HttpWebRequest Request { get; set; } 31privatebool ResponseFlag { get; set; } 32privatestring Result { get; set; } 33privatebool TimeoutFlag { get; set; } 34privateint TimeoutTime { get; set; } 35privatebool RetryFlag { get; set; } 36privateint RetryCount { get; set; } 37privateint WaitSleep { get; set; } 38privateint TrySleep { get; set; } 39 40// 初始化 41public Remoter() 42 { 43// 44 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; 45 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true); 46 47// 48this.URL = string.Empty; 49this.Request = default(HttpWebRequest); 50this.JsonContent = string.Empty; 51this.Buffer = default(byte[]); 52this.RequestStream = default(Stream); 53this.ResponseFlag = false; 54this.Result = string.Empty; 55this.TimeoutFlag = false; 56this.TimeoutTime = 10 * 1000; 57this.RetryFlag = false; 58this.RetryCount = 3; 59this.WaitSleep = 10; 60this.RequestMethod = "POST"; 61this.TrySleep = 2000; 62 } 63 64///<summary> 65/// 获取响应数据 66///</summary> 67publicstring GetRemoteData() 68 { 69// 70if(string.IsNullOrWhiteSpace(this.URL)) 71 { 72thrownew Exception("HttpAsync.URL,未赋值!"); 73 } 74 75// 76 RemoteNew(SetResult); 77 78// 79var timeNum = 0; 80while (true) 81 { 82if (ResponseFlag) 83 { 84break; 85 } 86if (TimeoutFlag) 87 { 88thrownew Exception(string.Format("请求超时!超时时间:{0}S", TimeoutTime / 1000)); 89 } 90 timeNum += WaitSleep; 91if (timeNum >= TimeoutTime) 92 { 93 TimeoutFlag = true; 94 } 95 Thread.Sleep(WaitSleep); 96 } 97 98// 99return Result; 100 } 101102//103privatevoid RemoteNew(Action<Remoter, string> action) 104 { 105// 106var reNum = 0; 107for (var i = 0; i < this.RetryCount; i++) 108 { 109try110 { 111// 112var uri = URL; 113114// 115this.Request = WebRequest.Create(uri) as HttpWebRequest; 116this.Request.KeepAlive = false; 117this.Request.Method = this.RequestMethod; 118this.Request.Credentials = CredentialCache.DefaultCredentials; 119if (this.RequestMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) 120 { 121this.Buffer = Encoding.UTF8.GetBytes(this.JsonContent); 122this.Request.ContentLength = this.Buffer.Length; 123this.Request.ContentType = "application/json"; 124this.RequestStream = this.Request.GetRequestStream(); 125this.RequestStream.Write(this.Buffer, 0, this.Buffer.Length); 126this.RequestStream.Close(); 127 } 128129// 130this.Request.BeginGetResponse((arr) => 131 { 132// 133var state = arr.AsyncState as Remoter; 134// 135var response = state.Request.EndGetResponse(arr) as HttpWebResponse; 136var respStream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8")); 137 action(state, respStream.ReadToEnd()); 138 respStream.Close(); 139 response.Close(); 140 }, this); 141// 142break; 143 } 144catch (Exception ex) 145 { 146 Thread.Sleep(this.TrySleep); 147 reNum++; 148if (reNum == this.RetryCount) 149 { 150thrownew Exception(string.Format("重试失败!重试次数:{0}次,失败原因:{1}", this.RetryCount, ex.Message)); 151 } 152continue; 153 } 154 } 155 } 156privatevoid SetResult(Remoter state, string jsonData) 157 { 158if (!string.IsNullOrWhiteSpace(jsonData)) 159 { 160 state.Result = jsonData; 161 state.ResponseFlag = true; 162 } 163 } 164 }
使用方式:
GET:
![技术分享](/upload/getfiles/default/2022/11/9/20221109024939739.jpg)
![技术分享](/upload/getfiles/default/2022/11/9/20221109024939760.jpg)
1 var remoter = new Remoter(); 2 remoter.RequestMethod = "GET"; 3 remoter.URL = "这里是你要请求的URL"; 4var response = remoter.GetRemoteData();
POST:
![技术分享](/upload/getfiles/default/2022/11/9/20221109024939739.jpg)
![技术分享](/upload/getfiles/default/2022/11/9/20221109024939760.jpg)
1 var remoter = new Remoter(); 2 remoter.RequestMethod = "POST"; 3 remoter.URL = "你要请求的URL"; 4 remoter.JsonContent = "你要想URL发送的JSON数据"; 5var response = remoter.GetRemoteData();
三、代码解析
四、计划中的开源项目...
原文:http://www.cnblogs.com/Meng-NET/p/5904129.html
内容总结
以上是互联网集市为您收集整理的【原创-算法-实现】异步HTTP请求操作全部内容,希望文章能够帮你解决【原创-算法-实现】异步HTTP请求操作所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。