1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- 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<HttpLangChaoTool>
- {
- Dictionary<string, string> requestHeader = new Dictionary<string, string>(); // header
- public void Post(string methodName, string jsonString, Action<string> CallBack)
- {
- StartCoroutine(SendHttp(methodName, jsonString, CallBack));
- }
- public IEnumerator SendHttp(string methodName, string jsonString, Action<string> 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");
- }
- }
|