UnityWebRequest前后端交互实现过程解析

这篇文章主要介绍了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 

工程中如何使用:封装请求、数据,注册委托,调用委托并添加回调

 //部分封装 public Action> 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(ref Action> 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(getUserResponds.data); UIMgr.Instance.CreateFrame("PersonalFrame"); }); });

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

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

四、总结

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

以上就是UnityWebRequest前后端交互实现过程解析的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程