HttpLangChaoTool.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. public class HttpLangChaoTool : MonoSingleton<HttpLangChaoTool>
  9. {
  10. Dictionary<string, string> requestHeader = new Dictionary<string, string>(); // header
  11. public void Post(string methodName, string jsonString, Action<string> CallBack)
  12. {
  13. StartCoroutine(SendHttp(methodName, jsonString, CallBack));
  14. }
  15. public IEnumerator SendHttp(string methodName, string jsonString, Action<string> CallBack, bool isPost = true, bool isCloud = false)
  16. {
  17. Debug.Log("Start Queue SendHttp " + methodName);
  18. string url;
  19. if (methodName.Contains("http"))
  20. {
  21. url = methodName;
  22. }
  23. else
  24. {
  25. url = HttpLangChaoAction.url + methodName;
  26. }
  27. Debug.Log("URL:" + url + " isPost " + isPost);
  28. UnityWebRequest webRequest;
  29. if (!isPost)
  30. {
  31. webRequest = UnityWebRequest.Get(url);
  32. }
  33. else
  34. {
  35. webRequest = new UnityWebRequest(url, "POST");
  36. }
  37. initHead();
  38. using (webRequest)
  39. {
  40. if (!isPost)
  41. {
  42. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  43. foreach (var v in requestHeader)
  44. {
  45. webRequest.SetRequestHeader(v.Key, v.Value);
  46. }
  47. }
  48. else
  49. {
  50. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  51. webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  52. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  53. }
  54. foreach (var v in requestHeader)
  55. {
  56. webRequest.SetRequestHeader(v.Key, v.Value);
  57. }
  58. yield return webRequest.SendWebRequest();
  59. Debug.Log("CallBack==>" + webRequest.downloadHandler.text);
  60. if (webRequest.isHttpError || webRequest.isNetworkError)
  61. {
  62. Debug.LogError(url + "\n" + webRequest.error + "\n" + webRequest.downloadHandler.text);
  63. string error = webRequest.downloadHandler.text;
  64. JObject jObject = JObject.Parse(error);
  65. CallBack(jObject["message"].ToString());
  66. }
  67. else
  68. {
  69. //Debug.Log(webRequest.downloadHandler.text);
  70. var mes = webRequest.downloadHandler.text;
  71. CallBack(mes);
  72. }
  73. }
  74. }
  75. public void initHead()
  76. {
  77. requestHeader.Clear();
  78. //if (UserInfo.Instance.Token != "" && UserInfo.Instance.Token != null)
  79. //{
  80. // requestHeader.Add("x-token", UserInfo.Instance.Token);
  81. // requestHeader.Add("authorization", UserInfo.Instance.Token);
  82. //}
  83. requestHeader.Add("Content-Type", "application/json");
  84. }
  85. }