using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.Networking; public class HttpLangChaoTool : MonoSingleton { Dictionary requestHeader = new Dictionary(); // header public void Post(string methodName, string jsonString, Action CallBack) { StartCoroutine(SendHttp(methodName, jsonString, CallBack)); } public IEnumerator SendHttp(string methodName, string jsonString, Action CallBack, bool isPost = true, bool isCloud = false) { Debug.Log("Start Queue SendHttp " + methodName); string url; if (methodName.Contains("http")) { url = methodName; } else { url = HttpLangChaoAction.url + methodName; } Debug.Log("URL:" + url + " isPost " + isPost); UnityWebRequest webRequest; if (!isPost) { webRequest = UnityWebRequest.Get(url); } else { webRequest = new UnityWebRequest(url, "POST"); } initHead(); using (webRequest) { if (!isPost) { webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); foreach (var v in requestHeader) { webRequest.SetRequestHeader(v.Key, v.Value); } } else { byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString); webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); } foreach (var v in requestHeader) { webRequest.SetRequestHeader(v.Key, v.Value); } yield return webRequest.SendWebRequest(); Debug.Log("CallBack==>" + webRequest.downloadHandler.text); if (webRequest.isHttpError || webRequest.isNetworkError) { Debug.LogError(url + "\n" + webRequest.error + "\n" + webRequest.downloadHandler.text); string error = webRequest.downloadHandler.text; JObject jObject = JObject.Parse(error); CallBack(jObject["message"].ToString()); } else { //Debug.Log(webRequest.downloadHandler.text); var mes = webRequest.downloadHandler.text; CallBack(mes); } } } public void initHead() { requestHeader.Clear(); //if (UserInfo.Instance.Token != "" && UserInfo.Instance.Token != null) //{ // requestHeader.Add("x-token", UserInfo.Instance.Token); // requestHeader.Add("authorization", UserInfo.Instance.Token); //} requestHeader.Add("Content-Type", "application/json"); } }