using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
namespace MotionFramework.Scripts.Runtime.Engine.Engine.Network.WebRequest
{
///
/// WebRequest ������
///
public sealed class WebRequestManager : ModuleSingleton, IModule
{
///
/// Get��ȡ�ı�
///
///
///
///
///
///
public async UniTask GetTextAsync(string url, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"获取数据异常 {request.error}");
return null;
}
return request.downloadHandler.text;
}
}
///
/// ��ȡͼƬ
///
///
///
///
///
///
public async UniTask GetImageAsync(string url, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
using (UnityWebRequest request = UnityWebRequestTexture.GetTexture(url))
{
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"�쳣�� {request.error}");
return null;
}
return DownloadHandlerTexture.GetContent(request);
}
}
///
/// ��ȡ��Ƶ
///
///
///
///
///
///
///
public async UniTask GetVideoAsync(string url, string localPath, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"�쳣�� {request.error}");
return null;
}
File.WriteAllBytes(localPath, request.downloadHandler.data);
return localPath;
}
}
///
/// ��ȡ�ļ�
///
///
///
///
///
///
public async UniTask GetFileAsync(string url, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"�쳣�� {request.error}");
return null;
}
return request.downloadHandler.data;
}
}
///
/// ��ȡ�ı�
///
///
///
///
///
///
///
public async UniTask PostTextAsync(string url, string jsonData, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
using (UnityWebRequest request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
{
byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(jsonData);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"�쳣�� {request.error}");
return null;
}
return request.downloadHandler.text;
}
}
///
/// ��ȡͼƬ
///
///
///
///
///
///
///
public async UniTask PostImageAsync(string url, string jsonData, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
using (UnityWebRequest request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
{
byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(jsonData);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerTexture();
request.SetRequestHeader("Content-Type", "application/json");
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"�쳣�� {request.error}");
return null;
}
return DownloadHandlerTexture.GetContent(request);
}
}
///
/// ��ȡ��Ƶ
///
///
///
///
///
///
///
///
public async UniTask PostVideoAsync(string url, string jsonData, string localPath, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
using (UnityWebRequest request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
{
byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(jsonData);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"�쳣�� {request.error}");
return null;
}
File.WriteAllBytes(localPath, request.downloadHandler.data);
return localPath;
}
}
///
/// 上传文件
///
/// 上传地址
/// 文件二进制数据
/// 文件名称
/// 认证令牌
/// 进度回调
/// 取消令牌
/// 服务器返回的数据
public async UniTask PostFileAsync(string url, byte[] fileData, string fileName = null, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
using (UnityWebRequest request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
{
// 使用文件二进制数据而不是JSON字符串
request.uploadHandler = new UploadHandlerRaw(fileData);
request.downloadHandler = new DownloadHandlerBuffer();
// 设置文件类型的Content-Type
request.SetRequestHeader("Content-Type", "application/octet-stream");
// 如果提供了文件名,设置Content-Disposition头
if (!string.IsNullOrEmpty(fileName))
{
request.SetRequestHeader("Content-Disposition", $"attachment; filename=\"{fileName}\"");
}
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"异常: {request.error}");
return null;
}
return request.downloadHandler.text;
}
}
///
/// 上传文件并同时提交表单参数
///
/// 上传地址
/// 文件二进制数据
/// 文件字段名
/// 文件名称
/// 表单字段集合
/// 认证令牌
/// 进度回调
/// 取消令牌
/// 服务器返回的数据
public async UniTask PostFileWithFormDataAsync(string url, byte[] fileData, string fileFieldName, string fileName, Dictionary formFields, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
WWWForm form = new WWWForm();
// 添加文件
form.AddBinaryData(fileFieldName, fileData, fileName);
// 添加表单字段
if (formFields != null)
{
foreach (var field in formFields)
{
form.AddField(field.Key, field.Value);
}
}
using (UnityWebRequest request = UnityWebRequest.Post(url, form))
{
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"异常: {request.error}, 详细信息: {request.downloadHandler.text}");
return null;
}
return request.downloadHandler.text;
}
}
///
/// ύ����
///
///
///
///
///
///
///
public async UniTask PostFormAsync(string url, Dictionary formFields, string token = null, Action onProgress = null, CancellationToken cancellationToken = default)
{
using (UnityWebRequest request = UnityWebRequest.Post(url, formFields))
{
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
await SendRequestWithProgress(request, onProgress, cancellationToken);
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"�쳣�� {request.error}");
return null;
}
return request.downloadHandler.text;
}
}
///
/// ����
///
///
///
///
///
private async UniTask SendRequestWithProgress(UnityWebRequest request, Action onProgress, CancellationToken cancellationToken)
{
// ��ȷʹ��await�����첽����
var operation = request.SendWebRequest();
// ѭ������Ƿ���ɣ������½���
while (!operation.isDone)
{
onProgress?.Invoke(request.downloadProgress);
await UniTask.Delay(100, cancellationToken: cancellationToken); // ÿ100�������һ�ν���
}
onProgress?.Invoke(1.0f);
// ���һ�ν��ȸ��£�ȷ��������ʾΪ100%
Debug.Log("Progress: 100%");
}
///
/// 使用multipart/form-data格式上传文件和参数
///
public async UniTask UploadFileWithFormData(string url, string filePath, string token = null)
{
if (!File.Exists(filePath))
{
Debug.LogError($"文件不存在: {filePath}");
return null;
}
try
{
byte[] fileData = File.ReadAllBytes(filePath);
// 获取文件名并转换为GB2312编码
string fileName = Path.GetFileName(filePath);
// 获取文件后缀名
string suffix = Path.GetExtension(filePath).TrimStart('.');
// 创建WWWForm对象来构建multipart/form-data请求
WWWForm form = new WWWForm();
// 添加文件,使用GB2312编码的文件名
form.AddBinaryData("file", fileData, Guid.NewGuid() + $".{suffix}");
// 添加所需的表单参数
form.AddField("stuId", "123");
form.AddField("appId", "taizhou123");
form.AddField("examId", "5555");
form.AddField("examinationId", "777777654");
// 创建使用form的请求
using (UnityWebRequest request = UnityWebRequest.Post(url, form))
{
// 添加授权头
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", $"Bearer {token}");
}
// 发送请求
await request.SendWebRequest();
// 处理响应
if (request.result == UnityWebRequest.Result.ConnectionError ||
request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"上传文件失败: {request.error}, 详细信息: {request.downloadHandler.text}");
return null;
}
else
{
return request.downloadHandler.text;
}
}
}
catch (Exception ex)
{
Debug.LogError($"上传文件时发生错误: {ex.Message}, {ex.StackTrace}");
return null;
}
}
public void OnCreate(object createParam)
{
}
public void OnUpdate()
{
}
public void OnDestroy()
{
}
public void OnGUI()
{
}
}
}