Files
plugin-library/Assets/00.StaryEvo/Runtime/Utility/WebRequestSystem.cs

94 lines
3.2 KiB
C#
Raw Normal View History

2025-03-31 11:16:52 +08:00
using System;
using System.Collections.Generic;
2025-03-31 14:55:24 +08:00
using System.Threading.Tasks;
2025-04-11 09:56:06 +08:00
using Cysharp.Threading.Tasks;
2025-03-31 11:16:52 +08:00
using UnityEngine;
using UnityEngine.Networking;
namespace Stary.Evo
{
public interface IWebRequestSystem
{
2025-03-31 14:55:24 +08:00
Task<string> Post(string url, string postData);
Task<string> Get(string url, string token=null);
2025-03-31 11:16:52 +08:00
}
public class WebRequestSystem : IWebRequestSystem
{
/// <summary>
/// POST请求数据
/// </summary>
/// <param name="url">获取Token值的服务URL地址很重要</param>
/// <param name="postData">传入请求的参数此处参数为JOSN格式</param>
/// <returns></returns>
2025-03-31 14:55:24 +08:00
public async Task<string> Post(string url, string postData)
2025-03-31 11:16:52 +08:00
{
using (UnityWebRequest webRequest = UnityWebRequest.Post(url, postData)) //第二种写法此行注释
{
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
webRequest.SetRequestHeader("Content-Type", "application/json");
await webRequest.SendWebRequest();
// 更新错误检查方式
if (webRequest.result == UnityWebRequest.Result.ConnectionError ||
webRequest.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError(webRequest.error);
return webRequest.error;
}
else
{
return webRequest.downloadHandler.text;
}
}
}
/// <summary>
/// GET请求数据
/// </summary>
/// <param name="url">请求数据的URL地址</param>
/// <param name="token">token验证的参数此处为authorization</param>
/// <returns></returns>
2025-03-31 14:55:24 +08:00
public async Task<string> Get(string url, string token=null)
2025-03-31 11:16:52 +08:00
{
try
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
webRequest.downloadHandler = new DownloadHandlerBuffer();
if (token != null)
webRequest.SetRequestHeader("Authorization", token); // 修正请求头名称规范
await webRequest.SendWebRequest();
// 增强错误处理
if (webRequest.result != UnityWebRequest.Result.Success)
{
var errorMsg = $"HTTP {webRequest.responseCode}\n" +
$"URL: {url}\n" +
$"Error: {webRequest.error}\n" +
$"Response: {webRequest.downloadHandler.text}";
Debug.LogError(errorMsg);
return null;
}
return webRequest.downloadHandler.text; // 添加返回值
}
}
catch (Exception e)
{
Debug.LogError(e);
}
return null;
}
2025-05-23 18:26:47 +08:00
2025-03-31 11:16:52 +08:00
}
}