当前位置:   article > 正文

Unity发送HTTP请求和文件下载_unity http下载

unity http下载

Unity发送HTTP请求和文件下载

本类库封装基于ulua框架LuaFramework

1. 使用的类库

HttpWebRequest
HttpWebResponse
LuaFramework

2. 实现了哪些功能

  • 发送GET、POST请求
  • HTTP请求异步化
  • 支持Lua回调
  • 支持Host,采用Proxy的实现方式
  • 支持将HTTP请求内容保存为文件
  • HTTP下载文件,支持断电续传

3. HTTP实现思路

  • HTTPRequest 发起HTTP请求,异步回调返回HTTPResponse
    HTTPRequest源码
  1. using System;
  2. using System.Net;
  3. using System.IO;
  4. using System.Text;
  5. using System.Collections.Generic;
  6. using LuaFramework;
  7. using UnityEngine;
  8. /// <summary>
  9. /// Http请求
  10. /// </summary>
  11. public class HTTPRequest
  12. {
  13. private string url;
  14. private int timeout;
  15. private Action<HTTPResponse> callback;
  16. private HttpWebRequest request;
  17. private string method;
  18. private string contentType;
  19. private KeyValuePair<string, int> proxy;
  20. protected int range = -1;
  21. // post内容
  22. private StringBuilder postBuilder;
  23. /// <summary>
  24. /// 错误代码
  25. /// </summary>
  26. public const int ERR_EXCEPTION = -1;
  27. /// <summary>
  28. /// 构造函数, 构造GET请求
  29. /// </summary>
  30. /// <param name="url">url地址</param>
  31. /// <param name="timeout">超时时间</param>
  32. /// <param name="callback">回调函数</param>
  33. public HTTPRequest (string url, string method, int timeout, Action<HTTPResponse> callback)
  34. {
  35. this.url = url;
  36. this.timeout = timeout;
  37. this.callback = callback;
  38. this.method = method.ToUpper();
  39. }
  40. /// <summary>
  41. /// 设置Post内容
  42. /// </summary>
  43. /// <param name="data">内容</param>
  44. public void SetPostData(string data) {
  45. if (postBuilder == null) {
  46. postBuilder = new StringBuilder (data.Length);
  47. }
  48. if (postBuilder.Length > 0) {
  49. postBu
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/95826
推荐阅读
相关标签
  

闽ICP备14008679号