Https.cs 1.6 KB

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