public class HttpHelper
{
public static async UniTask<(bool, string)> RequestGetUrlAsync(string url, bool debug = false)
{
Debug.Log($"req get url:{url}");
UnityWebRequest req = null;
req = UnityWebRequest.Get(url);
var rlt = await req.SendWebRequest();
await UniTask.WaitUntil(()=>rlt.isDone);
var error = rlt.error;
if (!string.IsNullOrEmpty(error))
{
Debug.LogError($"resp error:{error}");
return (false, error);
}
var text = rlt.downloadHandler.text;
if (debug)
{
Debug.Log($"resp ok:{text}");
}
return (true,text);
}
public static async UniTask<(bool, string)> RequestPostUrlAsync(string url,string data)
{
Debug.Log($"req post url:{url}");
UnityWebRequest req = null;
req = UnityWebRequest.Post(url,data);
var rlt = await req.SendWebRequest();
await UniTask.WaitUntil(()=>rlt.isDone);
//test
// await UniTask.WaitForSeconds(2);
var error = rlt.error;
if (!string.IsNullOrEmpty(error))
{
return (false, error);
}
return (true,rlt.downloadHandler.text);
}
}
文件下载
public class HttpFileDownloader
{
// 进度报告的委托
public delegate void ProgressReportDelegate(float progress);
private string _url;
private string _filePath;
private ProgressReportDelegate _progressCallback;
public HttpFileDownloader(string url, string filePath,ProgressReportDelegate progressCallback = null)
{
_url = url;
_filePath = filePath;
_progressCallback = progressCallback;
}
public async UniTask<(bool,string)> DownloadAsync(CancellationToken cancellationToken = default)
{
try
{
using (var webRequest = UnityWebRequest.Get(_url))
{
// 设置下载进度回调
if (_progressCallback != null)
{
webRequest.downloadHandler = new DownloadHandlerBuffer();
}
// 创建进度报告的 UniTask
UniTask progressReportTask = UniTask.Create(async () =>
{
while (!webRequest.isDone)
{
_progressCallback?.Invoke(webRequest.downloadProgress);
await UniTask.Yield(cancellationToken);
}
});
// 发送请求并等待完成,同时监听取消信号
var downloadTask = webRequest.SendWebRequest().ToUniTask(cancellationToken: cancellationToken);
await UniTask.WhenAny(downloadTask, progressReportTask);
// 检查是否被取消
if (cancellationToken.IsCancellationRequested)
{
webRequest.Abort();
return (false, "download aborted");
}
// 等待进度报告任务完成
if (_progressCallback != null)
{
await progressReportTask;
}
if (webRequest.isHttpError || webRequest.isNetworkError || !string.IsNullOrEmpty(webRequest.error))
{
Debug.LogError($"下载失败: {webRequest.error}");
return (false, webRequest.error);
}
byte[] results = webRequest.downloadHandler.data;
// 确保目录存在
string directory = Path.GetDirectoryName(_filePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// 写入文件
File.WriteAllBytes(_filePath, results);
Debug.Log($"文件已成功下载到: {_filePath}");
return (true, "");
}
}
catch (OperationCanceledException)
{
var msg = "下载已取消";
Debug.Log(msg);
return (false, msg);
}
catch (Exception ex)
{
var msg = ex.Message;
Debug.LogError(msg);
return (false, msg);
}
}
}
没有回复内容