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