unity 新版UnityWebRequest的使用


獲取時間戳(毫秒)

DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000

獲取時間戳(秒)

DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000

 

json解析需要下載LitJson依賴的庫文件,可以根據下方鏈接下載,

鏈接:https://pan.baidu.com/s/1o4WO8GfQOC_ha2E3sOLVNw
提取碼:abcd

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using LitJson;
using System;
using ApplicationManager;

namespace Module
{
    public class NetworkClient
    {
        public static void SendRequest(string key, string url, string method, bool needToken, string data, Action<string, string> callBack,
            Action<string, string> errorCallBack, int outTime = 30, int retry = 3, string contentType = "application/json")
        {
            JsonData json = new JsonData();
            UnityWebRequest webRequest = new UnityWebRequest();
            using (webRequest)
            {
                switch (method)
                {
                    case "GET":
                        {
                            if (!string.IsNullOrEmpty(data) && data != "[]")
                            {
                                json = JsonMapper.ToObject(data);
                            }
                            foreach (var p in json.Keys)
                            {
                                if (!url.Contains("?"))
                                {
                                    url = StringBuilderManager.getSingleton().AppendStringFormat("{0}?{1}{2}", url, p.ToString(), json[p].ToString());
                                }
                                else
                                {
                                    url = StringBuilderManager.getSingleton().AppendStringFormat("{0}&{1}{2}", url, p.ToString(), json[p].ToString());
                                }
                            }
                            webRequest = UnityWebRequest.Get(url);
                            break;
                        }
                    case "POST":
                        {
                            webRequest = new UnityWebRequest(url, method);
                            if (!string.IsNullOrEmpty(data))
                            {
                                var by = System.Text.Encoding.UTF8.GetBytes(data);
                                webRequest.uploadHandler = new UploadHandlerRaw(by) { contentType = contentType };
                                webRequest.downloadHandler = new DownloadHandlerBuffer();
                            }
                            break;
                        }
                }
                webRequest.timeout = outTime;
                webRequest.certificateHandler = new CertHandler();
                if (needToken)
                {
                    var token = GetToken();
                    webRequest.SetRequestHeader("token", token);
                    //獲取當前時間,單位ms
                    var time = $"{(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000}";
                    webRequest.SetRequestHeader("time", time);
                }

                Action<string, string> _callBack = (_key, _data) =>
                {
                    callBack?.Invoke(_key, _data);
                };
                Action<string, string> _errorCallBack = (_key, _data) =>
                {
                    if (retry > 0)
                    {
                        retry--;
                        SendRequest(key, url, method, needToken, data, callBack, errorCallBack, outTime, retry, contentType);
                    }
                    else
                    {
                        errorCallBack?.Invoke(_key, _data);
                    }
                };
                Core.FastCoroutine.getSingleton().AddCoroutine(SendRequest(key, webRequest, _callBack, _errorCallBack));
            }
        }

        public static IEnumerator SendRequest(string key, UnityWebRequest webRequest, Action<string, string> callBack, Action<string, string> errorCallBack)
        {
            if (webRequest != null)
            {
                webRequest.SendWebRequest();
                var time = (float)webRequest.timeout * 2;
                if (!webRequest.isDone && !webRequest.isHttpError && !webRequest.isNetworkError && time > 0)
                {
                    yield return null;
                    time = time - Time.deltaTime;
                }
                if (webRequest.isDone)
                {
                    if (!webRequest.isHttpError && !webRequest.isNetworkError)
                    {
                        try
                        {
                            callBack(key, webRequest.downloadHandler.text);
                        }
                        catch (Exception e)
                        {
                            Debug.LogError(e);
                        }
                    }
                    else
                    {
                        errorCallBack?.Invoke(key, webRequest.error);
                    }
                }
                else
                {
                    errorCallBack?.Invoke(key, webRequest.error ?? "timeOut");
                }
            }
            webRequest.Dispose();
            webRequest = null;
        }

        public static string GetToken()
        {
            return PlayerPrefs.GetString("token", "");
        }
    }
    public class CertHandler : CertificateHandler
    {
        protected override bool ValidateCertificate(byte[] certificateData)
        {
            return base.ValidateCertificate(certificateData);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM