Files
plugin-library/Assets/00.StaryEvo/Runtime/Utility/WebRequestSystem.cs
2025-03-31 14:55:24 +08:00

90 lines
3.2 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.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
namespace Stary.Evo
{
public interface IWebRequestSystem
{
Task<string> Post(string url, string postData);
Task<string> Get(string url, string token=null);
}
public class WebRequestSystem : IWebRequestSystem
{
/// <summary>
/// POST请求数据
/// </summary>
/// <param name="url">获取Token值的服务URL地址很重要</param>
/// <param name="postData">传入请求的参数此处参数为JOSN格式</param>
/// <returns></returns>
public async Task<string> Post(string url, string postData)
{
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>
public async Task<string> Get(string url, string token=null)
{
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;
}
}
}