UnityWebRequest进行前后端交互

一、技术概述

1、描述这个技术是做什么?

是Unity一套网络工具库,用于进行Http请求

2、学习该技术的原因?

项目需要,防止使用C#原生的网络库,加快开发速度

3、技术的难点在哪里

Unity仅提供了基础的功能,如何把这些功能构造成一个能够稳定业务开发的流程是一个比较难处理的问题

二、技术详情

描述你是如何实现和使用该技术的,要求配合代码和流程图详细描述。

  • HttpCenter类:封装Get、Post、Put、Delete,维护一个请求队列
///Get方法例举
private IEnumerator StartGet(HttpRequest request)
        {
            var url = request.Url + "?";
            //反射用来填充Url
            Type type = Type.GetType(request.MsgName);
            var Msg = Convert.ChangeType(request.Msg, type);
            PropertyInfo[] properties = Msg.GetType().GetProperties();
            for (int i = 0; i < properties.Length; i++)
            {
                url += $"{properties[i].Name}={properties[i].GetValue(Msg)}";
                if (i != properties.Length - 1)
                    url += "&";
            }
            request.Url = url;
            using (UnityWebRequest www = UnityWebRequest.Get(request.Url))
            {
                www.certificateHandler = new AcceptAllCertificatesSignedWithASpecificKeyPublicKey();
                www.downloadHandler = new DownloadHandlerBuffer();
                www.SetRequestHeader("Content-Type", "application/json");
                www.SetRequestHeader("token", token);
                yield return www.SendWebRequest();
                DealResult(www, request);
            }
  • 工程中如何使用:封装请求、数据,注册委托,调用委托并添加回调
    //部分封装
    public Action<LoginMsg, Action<HttpResponds>> NetLogin;
    public class LoginMsg : BaseMsg
    {
    public LoginMsg(string username, string password)
    {
        this.username = username;
        this.password = password;
    }
    public string username { get; set; }
    public string password { get; set; }
    }
    public class HttpResponds
    {
        public string data;
        public RespondsResult Result;
        public string token;
    }
    //注册委托
    AddListener(ref MsgManager.Instance.NetMsgCenter.NetLogin, Method.Post, "User/login");
    private void AddListener<T>(ref Action<T,Action<HttpResponds>> registerEvent,Method methodType,string url) where T:BaseMsg
    {
        registerEvent += (request, callback) =>
        {
            HttpRequest httpRequest = new HttpRequest()
            {
                Msg = request,
                HttpMethod = Method.Post,
                Url = HttpCenter.path + url,
                Handler = (responds) =>
                {
                    if (responds.Result == RespondsResult.Succ)
                    {
                        try
                        {
                            callback(responds);
                        }
                        catch(Exception ex)
                        {
                            
                            Debug.Log("窗口已销毁");
                            if(nowScene == 0)
                            {
                                SceneManager.LoadScene(1);
                            }
                            else
                            {
                                SceneManager.LoadScene(0);
                            }
                        }
                    }
                }
            };
            HttpCenter.Instance.Send(httpRequest);
        };
    }
    ///调用,添加回调
    MsgManager.Instance.NetMsgCenter.NetLogin(msg, (responds) =>
             {
                 HttpCenter.Instance.token = responds.token;
                 GetUserMsg userMsg = new GetUserMsg(accountField.text);
                 MsgManager.Instance.NetMsgCenter.NetGetUser(userMsg, (getUserResponds) =>
                  {
                      NetDataManager.Instance.user = JsonHelper.DeserializeObject<User>(getUserResponds.data);
                      UIMgr.Instance.CreateFrame("PersonalFrame");
                  });
             });

三、技术使用中遇到的问题和解决过程

关于WebRequest中有个奇怪的问题,至今未搞懂,但是有暂时的解决方法。问题是Post方法直接设置失效,需要先声明为Put,之后再www.method = UnityWebRequest.kHttpVerbPOST;

四、总结

主要是基于UnityWebRequest做了一些封装、利用反射、委托等特性来实现一些基本的功能

五、参考文献:

Unity官方文档,Unity WebRequest

猜你喜欢

转载自www.cnblogs.com/liulaoc/p/13190963.html