Tz2/Assets/Framework/Manager/WebRequestManager.cs

454 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
{
/// <summary>
/// WebRequest <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
public sealed class WebRequestManager : ModuleSingleton<WebRequestManager>, IModule
{
/// <summary>
/// Get<65><74>ȡ<EFBFBD>ı<EFBFBD>
/// </summary>
/// <param name="url"></param>
/// <param name="token"></param>
/// <param name="onProgress"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async UniTask<string> GetTextAsync(string url, string token = null, Action<float> 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;
}
}
/// <summary>
/// <20><>ȡͼƬ
/// </summary>
/// <param name="url"></param>
/// <param name="token"></param>
/// <param name="onProgress"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async UniTask<Texture2D> GetImageAsync(string url, string token = null, Action<float> 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($"<22><EFBFBD><ECB3A3> {request.error}");
return null;
}
return DownloadHandlerTexture.GetContent(request);
}
}
/// <summary>
/// <20><>ȡ<EFBFBD><C8A1>Ƶ
/// </summary>
/// <param name="url"></param>
/// <param name="localPath"></param>
/// <param name="token"></param>
/// <param name="onProgress"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async UniTask<string> GetVideoAsync(string url, string localPath, string token = null, Action<float> 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($"<22><EFBFBD><ECB3A3> {request.error}");
return null;
}
File.WriteAllBytes(localPath, request.downloadHandler.data);
return localPath;
}
}
/// <summary>
/// <20><>ȡ<EFBFBD>ļ<EFBFBD>
/// </summary>
/// <param name="url"></param>
/// <param name="token"></param>
/// <param name="onProgress"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async UniTask<byte[]> GetFileAsync(string url, string token = null, Action<float> 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($"<22><EFBFBD><ECB3A3> {request.error}");
return null;
}
return request.downloadHandler.data;
}
}
/// <summary>
/// <20><>ȡ<EFBFBD>ı<EFBFBD>
/// </summary>
/// <param name="url"></param>
/// <param name="jsonData"></param>
/// <param name="token"></param>
/// <param name="onProgress"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async UniTask<string> PostTextAsync(string url, string jsonData, string token = null, Action<float> 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($"<22><EFBFBD><ECB3A3> {request.error}");
return null;
}
return request.downloadHandler.text;
}
}
/// <summary>
/// <20><>ȡͼƬ
/// </summary>
/// <param name="url"></param>
/// <param name="jsonData"></param>
/// <param name="token"></param>
/// <param name="onProgress"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async UniTask<Texture2D> PostImageAsync(string url, string jsonData, string token = null, Action<float> 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($"<22><EFBFBD><ECB3A3> {request.error}");
return null;
}
return DownloadHandlerTexture.GetContent(request);
}
}
/// <summary>
/// <20><>ȡ<EFBFBD><C8A1>Ƶ
/// </summary>
/// <param name="url"></param>
/// <param name="jsonData"></param>
/// <param name="localPath"></param>
/// <param name="token"></param>
/// <param name="onProgress"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async UniTask<string> PostVideoAsync(string url, string jsonData, string localPath, string token = null, Action<float> 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($"<22><EFBFBD><ECB3A3> {request.error}");
return null;
}
File.WriteAllBytes(localPath, request.downloadHandler.data);
return localPath;
}
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="url">上传地址</param>
/// <param name="fileData">文件二进制数据</param>
/// <param name="fileName">文件名称</param>
/// <param name="token">认证令牌</param>
/// <param name="onProgress">进度回调</param>
/// <param name="cancellationToken">取消令牌</param>
/// <returns>服务器返回的数据</returns>
public async UniTask<string> PostFileAsync(string url, byte[] fileData, string fileName = null, string token = null, Action<float> 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;
}
}
/// <summary>
/// 上传文件并同时提交表单参数
/// </summary>
/// <param name="url">上传地址</param>
/// <param name="fileData">文件二进制数据</param>
/// <param name="fileFieldName">文件字段名</param>
/// <param name="fileName">文件名称</param>
/// <param name="formFields">表单字段集合</param>
/// <param name="token">认证令牌</param>
/// <param name="onProgress">进度回调</param>
/// <param name="cancellationToken">取消令牌</param>
/// <returns>服务器返回的数据</returns>
public async UniTask<string> PostFileWithFormDataAsync(string url, byte[] fileData, string fileFieldName, string fileName, Dictionary<string, string> formFields, string token = null, Action<float> 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;
}
}
/// <summary>
/// ύ<><E1BDBB><EFBFBD><EFBFBD>
/// </summary>
/// <param name="url"></param>
/// <param name="formFields"></param>
/// <param name="token"></param>
/// <param name="onProgress"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async UniTask<string> PostFormAsync(string url, Dictionary<string, string> formFields, string token = null, Action<float> 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($"<22><EFBFBD><ECB3A3> {request.error}");
return null;
}
return request.downloadHandler.text;
}
}
/// <summary>
/// <20><><EFBFBD><EFBFBD>
/// </summary>
/// <param name="request"></param>
/// <param name="onProgress"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async UniTask SendRequestWithProgress(UnityWebRequest request, Action<float> onProgress, CancellationToken cancellationToken)
{
// <20><>ȷʹ<C8B7><CAB9>await<69><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD><ECB2BD><EFBFBD><EFBFBD>
var operation = request.SendWebRequest();
// ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD>ɣ<EFBFBD><C9A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD>½<EFBFBD><C2BD><EFBFBD>
while (!operation.isDone)
{
onProgress?.Invoke(request.downloadProgress);
await UniTask.Delay(100, cancellationToken: cancellationToken); // ÿ100<30><30><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD>ν<EFBFBD><CEBD><EFBFBD>
}
onProgress?.Invoke(1.0f);
// <20><><EFBFBD>һ<EFBFBD>ν<EFBFBD><CEBD>ȸ<EFBFBD><C8B8>£<EFBFBD>ȷ<EFBFBD><C8B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʾΪ100%
Debug.Log("Progress: 100%");
}
/// <summary>
/// 使用multipart/form-data格式上传文件和参数
/// </summary>
public async UniTask<string> 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()
{
}
}
}