using System.Collections; using UnityEngine; using System; using UnityEngine.Networking; using System.Text; using GFGGame.Launcher; using System.Reflection; namespace GFGGame { /// /// Http Request SDK /// public class HttpTool : SingletonMonoBase { public void Get(string url, Action callback, bool showWrong = true) { StartCoroutine(GetRequest(url, callback, showWrong)); } public void Get(string prefixUrl, string methodName, Action callback, bool showWrong = true) { string url = prefixUrl + methodName; StartCoroutine(GetRequest(url, callback, showWrong)); } public IEnumerator GetRequest(string url, Action callback, bool showWrong) { ET.Log.Debug("get url : " + url); using (UnityWebRequest webRequest = UnityWebRequest.Get(url)) { webRequest.timeout = LauncherConfig.HTTP_GET_TIME_OUT; yield return webRequest.SendWebRequest(); ResultHandler(webRequest, callback, url, () => { Get(url, callback); }, showWrong); } } public void Post(string url, string body, Action callback = null, string contentType = "application/text", bool showWrong = false) { StartCoroutine(PostRequest(url, body, callback, contentType, showWrong)); } public void Post(string prefixUrl, string methodName, string body, Action callback = null, string contentType = "application/text", bool showWrong = false) { string url = prefixUrl + methodName; Post(url, body, callback, contentType); } private IEnumerator PostRequest(string url, string body, Action callback, string contentType, bool showWrong) { ET.Log.Debug(string.Format("post url:{0} postData:{1}", url, body)); using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST")) { byte[] bodyRaw = Encoding.UTF8.GetBytes(body); webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); webRequest.timeout = LauncherConfig.HTTP_POST_TIME_OUT; //http header 的内容 webRequest.SetRequestHeader("Content-Type", contentType); // webRequest.timeout; yield return webRequest.SendWebRequest(); ResultHandler(webRequest, callback, body, () => { Post(url, body, callback); }, showWrong); } } public void ResultHandler(UnityWebRequest webRequest, Action callback, string tag, Action retryCall, bool showWrong) { string paramCallback = null; if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError) { ET.Log.Error(webRequest.error + "\n" + webRequest.downloadHandler.text); if(showWrong) { Alert.Show("连接服务器失败:\n请检查网络和服务器状态") .SetRightButton(true, "重试", (object data) => { retryCall(); }); } } else { ET.Log.Debug("from server " + webRequest.downloadHandler.text + "\nby " + tag); paramCallback = webRequest.downloadHandler.text; //paramCallback = System.Text.Encoding.UTF8.GetString(webRequest.downloadHandler.data, 3, webRequest.downloadHandler.data.Length - 3); callback?.Invoke(paramCallback); } } } }