CxHttp.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections;
  3. using System.Net.Http;
  4. using System.Text;
  5. using JetBrains.Annotations;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. namespace Plugins.CxShine.net
  9. {
  10. public class CxHttp
  11. {
  12. public static IEnumerator HttpPost(string url, string postData, Action<string> successAction,
  13. Action<UnityWebRequest.Result> errorAction)
  14. {
  15. return _http_request(url, "POST", postData, successAction, errorAction);
  16. }
  17. public static IEnumerator HttpGet(string url, Action<string> successAction,
  18. Action<UnityWebRequest.Result> errorAction)
  19. {
  20. return _http_request(url, "GET", null, successAction, errorAction);
  21. }
  22. [CanBeNull]
  23. private static IEnumerator _http_request(string url, string method,
  24. string postData,
  25. Action<string> responseAction, Action<UnityWebRequest.Result> errorAction)
  26. {
  27. using (var uwr = new UnityWebRequest(url, method))
  28. {
  29. // add upload data if POST
  30. if ("POST" == method)
  31. {
  32. var postBytes = Encoding.UTF8.GetBytes(postData);
  33. uwr.uploadHandler = new UploadHandlerRaw(postBytes);
  34. }
  35. uwr.timeout = 5;
  36. uwr.downloadHandler = new DownloadHandlerBuffer();
  37. uwr.SetRequestHeader("Content-Type", "application/json");
  38. yield return uwr.SendWebRequest();
  39. switch (uwr.result)
  40. {
  41. case UnityWebRequest.Result.ConnectionError:
  42. case UnityWebRequest.Result.ProtocolError:
  43. case UnityWebRequest.Result.DataProcessingError:
  44. Debug.Log(uwr.error);
  45. errorAction?.Invoke(uwr.result);
  46. break;
  47. case UnityWebRequest.Result.Success:
  48. {
  49. var responseText = uwr.downloadHandler.text;
  50. // Debug.Log("Status Code:" + uwr.responseCode + " request.url:" +
  51. // uwr.uri + "request.data:" + postData +
  52. // "request.resp:" + responseText);
  53. responseAction?.Invoke(responseText);
  54. break;
  55. }
  56. case UnityWebRequest.Result.InProgress:
  57. break;
  58. default:
  59. throw new ArgumentOutOfRangeException();
  60. }
  61. }
  62. }
  63. }
  64. }