123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- using System.Collections;
- using UnityEngine;
- using System;
- using UnityEngine.Networking;
- using System.Text;
- using GFGGame.Launcher;
- namespace GFGGame
- {
- /// <summary>
- /// Http Request SDK
- /// </summary>
- public class HttpTool : SingletonMonoBase<HttpTool>
- {
- public void Get(string prefixUrl, string methodName, Action<string> callback)
- {
- StartCoroutine(GetRequest(prefixUrl, methodName, callback));
- }
- public IEnumerator GetRequest(string prefixUrl, string methodName, Action<string> callback)
- {
- string url = prefixUrl + methodName;
- Debug.Log("get url : " + url);
- using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
- {
- webRequest.timeout = LauncherConfig.HTTP_GET_TIME_OUT;
- yield return webRequest.SendWebRequest();
- ResultHandler(webRequest, callback, prefixUrl, () =>
- {
- Get(prefixUrl, methodName, callback);
- });
- }
- }
- //jsonString 为json字符串,post提交的数据包为json
- public void Post(string prefixUrl, string methodName, string jsonString, Action<string> callback)
- {
- StartCoroutine(PostRequest(prefixUrl, methodName, jsonString, callback));
- }
- public IEnumerator PostRequest(string prefixUrl, string methodName, string jsonString, Action<string> callback)
- {
- string url = prefixUrl + methodName;
- Debug.Log(string.Format("post url:{0} postData:{1}", url, jsonString));
- using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
- {
- byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
- webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
- webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
- webRequest.timeout = LauncherConfig.HTTP_POST_TIME_OUT;
- //http header 的内容
- webRequest.SetRequestHeader("Content-Type", "application/json");
- // webRequest.timeout;
- yield return webRequest.SendWebRequest();
- ResultHandler(webRequest, callback, jsonString, () =>
- {
- Post(prefixUrl, methodName, jsonString, callback);
- });
- }
- }
- public void ResultHandler(UnityWebRequest webRequest, Action<string> callback, string tag, Action retryCall)
- {
- string paramCallback = null;
- if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
- {
- Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
- Alert.Show("连接服务器失败:\n请检查网络和服务器状态")
- .SetRightButton(true, "重试", (object data) =>
- {
- retryCall();
- });
- }
- else
- {
- Debug.Log("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);
- }
- }
- }
- }
|