当前位置:   article > 正文

Unity-Http协议请求下载系列2:HttpWebRequest封装_unity begingetresponse

unity begingetresponse

上篇文章介绍了Http请求的接口封装,本篇具体介绍基于HttpWebRequest接口实现的资源请求下载。HttpWebRequestHelper实现完全重新请求下载和断点续传,并且是异步多线程执行的。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Net;
  5. using System.IO;
  6. using System.Text;
  7. using System;
  8. using System.Threading;
  9. /*
  10. * Author:W
  11. * .NET的网络请求下载接口
  12. */
  13. namespace W.GameFramework.HotUpdate
  14. {
  15. public class HttpWebRequestHelper : HttpHelper
  16. {
  17. private HttpWebRequest httpWebRequest = null;
  18. private HttpWebResponse httpWebResponse = null;
  19. private Thread requestThread = null;
  20. private FileStream fileStream = null;
  21. private Stream responseStream = null;
  22. public override void SendHttpRequest(string url, string path, DownloadType downloadType = DownloadType.New, OnDownloadBeginHandler onDownloadBeginHandler = null, OnDownloadEndHandler onDownloadEndHandler = null,
  23. OnDownloadProgressHanlder onDownloadProgressHanlder = null, OnDownloadErrorHandler onDownloadErrorHandler = null)
  24. {
  25. base.SendHttpRequest(url, path,downloadType, onDownloadBeginHandler, onDownloadEndHandler,onDownloadProgressHanlder, onDownloadErrorHandler);
  26. if (downloadType == DownloadType.New)
  27. {
  28. SendHttpRequestByNew();
  29. }
  30. else if (downloadType == DownloadType.Continue)
  31. {
  32. SendHttpRequestByContinue();
  33. }
  34. }
  35. #region 异步请求下载【完整重新下载】
  36. /// <summary>
  37. /// 请求下载:完整重新下载
  38. /// </summary>
  39. private void SendHttpRequestByNew()
  40. {
  41. try
  42. {
  43. httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
  44. httpWebRequest.Timeout = timeOut;
  45. httpWebRequest.Method = method;
  46. AsyncCallback asyncCallback = new AsyncCallback(OnResponseCallBack);
  47. httpWebRequest.BeginGetResponse(asyncCallback, null);
  48. //文件请求下载开始回调
  49. if (OnDownloadBeginHandler != null)
  50. OnDownloadBeginHandler();
  51. }
  52. catch (Exception e)
  53. {
  54. //文件请求下载错误回调
  55. if (OnDownloadErrorHandler != null)
  56. OnDownloadErrorHandler(e.Message);
  57. if (httpWebRequest != null)
  58. httpWebRequest.Abort();
  59. }
  60. }
  61. /// <summary>
  62. /// 异步请求返回结果处理
  63. /// </summary>
  64. /// <param name="asyncResult"></param>
  65. private void OnResponseCallBack(IAsyncResult asyncResult)
  66. {
  67. try
  68. {
  69. httpWebResponse = httpWebRequest.EndGetResponse(asyncResult) as HttpWebResponse;
  70. //计算请求加载的文件总长度
  71. fileLength = httpWebResponse.ContentLength;
  72. if (httpWebResponse.StatusCode == HttpStatusCode.OK)
  73. {
  74. //检查本地是否缓存请求下载文件,如果有则删除
  75. if (File.Exists(path))
  76. File.Delete(path);
  77. fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
  78. //计算文件本地已加载的长度
  79. fileCurLength = fileStream.Length;
  80. progress = (float)fileCurLength / fileLength;
  81. //请求内容Byte数据读取
  82. responseStream = httpWebResponse.GetResponseStream();
  83. byte[] readBuff = new byte[2048];
  84. int len = -1;
  85. while ((len = responseStream.Read(readBuff, 0, readBuff.Length)) > 0)
  86. {
  87. //停止请求下载
  88. if (IsStop)
  89. {
  90. Clear();
  91. return;
  92. }
  93. fileStream.Write(readBuff, 0, len);
  94. fileCurLength += len;
  95. progress = (float)fileCurLength / fileLength;
  96. }
  97. //文件请求下载完成回调
  98. if (OnDownloadEndHandler != null)
  99. OnDownloadEndHandler();
  100. }
  101. else
  102. {
  103. //文件请求下载错误回调
  104. if (OnDownloadErrorHandler != null)
  105. OnDownloadErrorHandler(httpWebResponse.StatusDescription);
  106. }
  107. }
  108. catch (Exception e)
  109. {
  110. //文件请求下载错误回调
  111. if (OnDownloadErrorHandler != null)
  112. OnDownloadErrorHandler(e.Message);
  113. }
  114. finally
  115. {
  116. Clear();
  117. }
  118. }
  119. #endregion
  120. #region 开线程请求下载【断点续传下载】
  121. /// <summary>
  122. /// 请求下载 【断点续传下载时】
  123. /// </summary>
  124. private void SendHttpRequestByContinue()
  125. {
  126. requestThread = new Thread(AsyncSendHttpRequest);
  127. requestThread.IsBackground = false;
  128. requestThread.Start();
  129. }
  130. /// <summary>
  131. /// 多线程异步请求下载
  132. /// </summary>
  133. private void AsyncSendHttpRequest()
  134. {
  135. try
  136. {
  137. fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
  138. //计算请求下载文件本地已缓存的数据大小
  139. fileCurLength = fileStream.Length;
  140. //先发出请求,获取请求下载的文件大小信息
  141. httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
  142. httpWebRequest.Method = "HEAD";
  143. httpWebRequest.Timeout = timeOut;
  144. httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
  145. if (httpWebResponse.StatusCode == HttpStatusCode.OK)
  146. {
  147. //计算请求下载文件总的大小
  148. fileLength = httpWebResponse.ContentLength;
  149. progress = (float)fileCurLength / fileLength;
  150. if (OnDownloadBeginHandler != null)
  151. OnDownloadBeginHandler();
  152. //说明请求下载文件未完成下载,请继续接着下载
  153. if (progress < 1f)
  154. {
  155. //设定文件写入流的开始写入位置
  156. fileStream.Seek(fileCurLength, SeekOrigin.Begin);
  157. httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
  158. httpWebRequest.Method = method;
  159. httpWebRequest.Timeout = timeOut;
  160. //向请求声明下载文件下载开始位置
  161. httpWebRequest.AddRange((int)fileCurLength);
  162. //请求返回
  163. httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
  164. if (httpWebResponse.StatusCode == HttpStatusCode.OK
  165. || httpWebResponse.StatusCode == HttpStatusCode.PartialContent)
  166. {
  167. responseStream = httpWebResponse.GetResponseStream();
  168. byte[] readBuff = new byte[2048];
  169. int len = -1;
  170. while ((len = responseStream.Read(readBuff, 0, readBuff.Length)) > 0)
  171. {
  172. //停止请求下载
  173. if (IsStop)
  174. {
  175. Clear();
  176. return;
  177. }
  178. fileStream.Write(readBuff, 0, len);
  179. fileCurLength += len;
  180. progress = (float)fileCurLength / fileLength;
  181. }
  182. if (OnDownloadEndHandler != null)
  183. OnDownloadEndHandler();
  184. }
  185. else
  186. {
  187. if (OnDownloadErrorHandler != null)
  188. OnDownloadErrorHandler(httpWebResponse.StatusDescription);
  189. }
  190. }
  191. else
  192. {
  193. progress = 1f;
  194. if (OnDownloadEndHandler != null)
  195. OnDownloadEndHandler();
  196. }
  197. }
  198. else
  199. {
  200. if (OnDownloadErrorHandler != null)
  201. OnDownloadErrorHandler(httpWebResponse.StatusDescription);
  202. }
  203. }
  204. catch (Exception e)
  205. {
  206. if (OnDownloadErrorHandler != null)
  207. OnDownloadErrorHandler(e.Message);
  208. }
  209. finally
  210. {
  211. Clear();
  212. }
  213. }
  214. #endregion
  215. public override void Clear()
  216. {
  217. if (responseStream != null)
  218. {
  219. responseStream.Close();
  220. responseStream = null;
  221. }
  222. if (httpWebResponse != null)
  223. {
  224. httpWebResponse.Close();
  225. httpWebResponse = null;
  226. }
  227. if (httpWebRequest != null)
  228. {
  229. httpWebRequest.Abort();
  230. httpWebRequest = null;
  231. }
  232. if (fileStream != null)
  233. {
  234. fileStream.Flush();
  235. fileStream.Close();
  236. fileStream = null;
  237. }
  238. if (requestThread != null)
  239. {
  240. requestThread.Abort();
  241. requestThread = null;
  242. }
  243. }
  244. }
  245. }

下篇文章链接https://blog.csdn.net/wlqchengzhangji/article/details/118704731

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/259374
推荐阅读
相关标签
  

闽ICP备14008679号