Unity发送HTTP请求和文件下载
本类库封装基于ulua框架LuaFramework
1. 使用的类库
HttpWebRequest
HttpWebResponse
LuaFramework
2. 实现了哪些功能
- 发送GET、POST请求
- HTTP请求异步化
- 支持Lua回调
- 支持Host,采用Proxy的实现方式
- 支持将HTTP请求内容保存为文件
- HTTP下载文件,支持断电续传
3. HTTP实现思路
HTTPRequest
发起HTTP请求,异步回调返回HTTPResponse
HTTPRequest
源码
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Generic;
using LuaFramework;
using UnityEngine;
/// <summary>
/// Http请求
/// </summary>
public class HTTPRequest
{
private string url;
private int timeout;
private Action<HTTPResponse> callback;
private HttpWebRequest request;
private string method;
private string contentType;
private KeyValuePair<string, int> proxy;
protected int range = -1;
// post内容
private StringBuilder postBuilder;
/// <summary>
/// 错误代码
/// </summary>
public const int ERR_EXCEPTION = -1;
/// <summary>
/// 构造函数, 构造GET请求
/// </summary>
/// <param name="url">url地址</param>
/// <param name="timeout">超时时间</param>
/// <param name="callback">回调函数</param>
public HTTPRequest (string url, string method, int timeout, Action<HTTPResponse> callback)
{
this.url = url;
this.timeout = timeout;
this.callback = callback;
this.method = method.ToUpper();
}
/// <summary>
/// 设置Post内容
/// </summary>
/// <param name="data">内容</param>
public void SetPostData(string data) {
if (postBuilder == null) {
postBuilder = new StringBuilder (data.Length);
}
if (postBuilder.Length > 0