Https.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #if UNITY_EDITOR
  2. using Cysharp.Threading.Tasks;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Text;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. public static class Https
  9. {
  10. public static async UniTask<T> POST<T>(string url, string body, Action<string> onRequestError = null)
  11. {
  12. using UnityWebRequest req = UnityWebRequest.PostWwwForm(url, string.Empty);
  13. req.disposeUploadHandlerOnDispose = true;
  14. req.downloadHandler = new DownloadHandlerBuffer();
  15. AppRuntimes.Log($"request url:{url} body:{body} ");
  16. req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(body));
  17. req.SetRequestHeader("Content-Type", "application/json");
  18. try
  19. {
  20. var result = await req.SendWebRequest();
  21. if (result.result != UnityWebRequest.Result.Success)
  22. {
  23. Debug.LogError(
  24. $"POST request failed. url:{url} error:{result.error} " +
  25. $"responseCode:{result.responseCode}");
  26. onRequestError?.Invoke(result.error);
  27. return default(T);
  28. }
  29. var response = JsonConvert.DeserializeObject<T>(result.downloadHandler.text);
  30. AppRuntimes.Log($"request url:{url} response:{result.downloadHandler.text}");
  31. return response;
  32. }
  33. catch (System.Exception e)
  34. {
  35. if (e.GetType() == typeof(UnityWebRequestException))
  36. {
  37. onRequestError?.Invoke("request error!");
  38. }
  39. UnityEngine.Debug.LogError(e);
  40. return default(T);
  41. }
  42. }
  43. }
  44. #endif