using Cysharp.Threading.Tasks; using UnityEngine; using UnityEngine.Networking; using System.Text; using Newtonsoft.Json; /// /// 异步封装unityWebRequest请求 /// public static class AsyncWebReq { public static async UniTask Get(string endpoint) { var getRequest = CreateRequest(endpoint); await getRequest.SendWebRequest(); #if UNITY_EDITOR Debug.Log("async req : " + getRequest.downloadHandler.text); #endif T result = JsonUtility.FromJson(getRequest.downloadHandler.text); getRequest.Dispose(); return result; } public static async UniTask Post(string endpoint, object payload) { var postRequest = CreateRequest(endpoint, RequestType.POST, payload); await postRequest.SendWebRequest(); #if UNITY_EDITOR Debug.Log("async req : " + postRequest.downloadHandler.text); Debug.Log("endpoint : " + endpoint); #endif T result = JsonUtility.FromJson(postRequest.downloadHandler.text); postRequest.Dispose(); return result; } private static UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null) { var request = new UnityWebRequest(path, type.ToString()); if (data != null) { string reqJson = JsonConvert.SerializeObject(data); #if UNITY_EDITOR Debug.Log($"async req json : {reqJson}"); #endif var bodyRaw = Encoding.UTF8.GetBytes(reqJson); request.uploadHandler = new UploadHandlerRaw(bodyRaw); } request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); return request; } private static void AttachHeader(UnityWebRequest request, string key, string value) { request.SetRequestHeader(key, value); } /// /// 请求类型 /// public enum RequestType { GET = 0, POST = 1 } }