| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- using Cysharp.Threading.Tasks;
- using Newtonsoft.Json;
- using System;
- using System.Text;
- using UnityEngine;
- using UnityEngine.Networking;
- public static class Https
- {
- public static async UniTask<T> POST<T>(string url, string body, Action<string> onRequestError = null)
- {
- using UnityWebRequest req = UnityWebRequest.PostWwwForm(url, string.Empty);
- req.disposeUploadHandlerOnDispose = true;
- req.downloadHandler = new DownloadHandlerBuffer();
- AppRuntimes.Log($"request url:{url} body:{body} ");
- req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(body));
- req.SetRequestHeader("Content-Type", "application/json");
- try
- {
- var result = await req.SendWebRequest();
- if (result.result != UnityWebRequest.Result.Success)
- {
- Debug.LogError(
- $"POST request failed. url:{url} error:{result.error} " +
- $"responseCode:{result.responseCode}");
- onRequestError?.Invoke(result.error);
- return default(T);
- }
- var response = JsonConvert.DeserializeObject<T>(result.downloadHandler.text);
- AppRuntimes.Log($"request url:{url} response:{result.downloadHandler.text}");
- return response;
- }
- catch (System.Exception e)
- {
- if (e.GetType() == typeof(UnityWebRequestException))
- {
- onRequestError?.Invoke("request error!");
- }
- UnityEngine.Debug.LogError(e);
- return default(T);
- }
- }
- }
|