Unity UnityWebRequest实现与后端的交互

一般我们与后端对接的时候会用到UnityWebRequest
这里简单使用这个与后端进行交互
这个是总类

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

public enum EOPERATION
{
    LOGIN = 0,//登录
    REGISTER,//注册
    COLLEGELIST, //学院
    MAJORLIST, //专业
    CLASSLIST,//班级
    EXISTMAIL,//邮箱重复验证
    EXISTNUMBER, //学号重复验证
    GETPASSWORD,//忘记密码
    ADDSCORE,//添加成绩
    DownLoad,
}
public class CallBackUser
{
    public bool success;
    public string msg;
    public User obj;
}
public class WebWork : MonoBehaviour
{
    Dictionary<EOPERATION, Action<string, DownloadHandler>> _handers = new Dictionary<EOPERATION, Action<string, DownloadHandler>>();
    private string filepath;
    bool isStartDownload;
    UnityWebRequest request;
    //根据协议号获取地址后缀
    Dictionary<EOPERATION, string> mURLs = new Dictionary<EOPERATION, string>{
        { EOPERATION.LOGIN,"webapi/login" },
        { EOPERATION.REGISTER,"webapi/register"},
        { EOPERATION.COLLEGELIST,"user/college/list_combo"},
        { EOPERATION.MAJORLIST,"user/major/list_combo"},
        { EOPERATION.CLASSLIST,"user/class/list_combo"},
        { EOPERATION.EXISTMAIL,"webapi/existemail"},
        { EOPERATION.EXISTNUMBER,"webapi/existnumber"},
        {EOPERATION.GETPASSWORD, "webapi/forget_pass"},
        {EOPERATION.ADDSCORE,"webapi/add_score"},
        {EOPERATION.DownLoad,"" }
    };

    private string ipAddress = "http://192.168.40.153:8000/";

    AccountHander accountHander = new AccountHander();

    public object JsonConvert { get; private set; }

    //在这里注册消息返回后分发处理
    public void Init()
    {
        accountHander.RegisterMsg(_handers);
        DontDestroyOnLoad(this);
    }
    /// <summary>
    /// 传输数据
    /// </summary>
    /// <param name="dic"></param>
    /// <param name="op"></param>
    public void SendPost(EOPERATION op, Dictionary<string, string> dic)
    {
        //根据协议号获取完整路径
        string url = ipAddress + mURLs[op];
        StartCoroutine(Post(url, dic, op));
    }

    /// <summary>
    /// 获取数据
    /// </summary>
    /// <param name="op"></param>
    public void SendGet(EOPERATION op, string name = "")
    {
        string url = ipAddress + mURLs[op] + "/" + name;
        StartCoroutine(Get(url, op, name));
    }
    /// <summary>
    /// 获取下载进度
    /// </summary>
    /// <returns></returns>
    public float GetProgress()
    {
        if (request == null || !isStartDownload)
            return 0;
        return request.downloadProgress;
    }

    private IEnumerator Get(string url, EOPERATION op, string name)
    {

        if (!string.IsNullOrEmpty(url))
        {
            using (request = UnityWebRequest.Get(url))
            {
                isStartDownload = true;
                //设置超时 链接超时返回 且isNetworkError为true
                request.timeout = 30;
                yield return request.SendWebRequest();
                isStartDownload = false;
                //结果回传给具体实现
                if (request.isHttpError || request.isNetworkError)
                {
                    Debug.Log(request.error);
                }
                else
                {
                    _handers[op](name, request.downloadHandler);
                }
            };
        }
    }
    //private WWW http;
    private IEnumerator Post(string url, Dictionary<string, string> dic, EOPERATION op)
    {
        if (!string.IsNullOrEmpty(url))
        {
            WWWForm form = new WWWForm();

            foreach (var item in dic)
            {
                form.AddField(item.Key, item.Value);
            }
            using (request = UnityWebRequest.Post(url, form))
            {
                yield return request.SendWebRequest();
                //结果回传给具体实现
                if (request.isHttpError || request.isNetworkError)
                {
                    Debug.Log(request.error);
                }
                else
                {
                    _handers[op](name, request.downloadHandler);
                }
            }
        }
    }
}

工具类

using System.IO;

public class FileTool
{
    /// <summary>
    /// 创建文件
    /// </summary>
   public static void CreateFile(string filePath,byte[]bytes)
    {
        using (FileStream fs = new FileStream(filePath,FileMode.Create,FileAccess.Write))
        {
            fs.Write(bytes, 0, bytes.Length);
        }       
    }
}

消息返回处理类 这只是一个分类

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class AccountHander
{

    public void RegisterMsg(Dictionary<EOPERATION, Action<string,DownloadHandler>> handers)
    {
        handers.Add(EOPERATION.LOGIN, OnRspLogin);
        handers.Add(EOPERATION.REGISTER, OnRspRegister);
        handers.Add(EOPERATION.DownLoad, OnRspDownLoad);
    }

    private void OnRspLogin(string name,DownloadHandler data)
    {
        //用Json转化为类内部数据
        JsonConvert.DeserializeObject<CallBackUser>(data.text);

    }
    private void OnRspRegister(string name,DownloadHandler data)
    {

    }

    private void OnRspDownLoad(string name,DownloadHandler data)
    {
        //data.data二进制的文件 视频 图片的信息
        FileTool.CreateFile(name, data.data);
    }
 
}


   public void RegisterMsg(Dictionary<EOPERATION, Action<string,DownloadHandler>> handers)
 {

}

如果想添加一个新的就在主类Init里注册 然后新类写一个注册方法就行了 这样会自动根据枚举转到相应的处理函数
然后name的话只是为了区分下载文件起码要改名吧 不然不知道名字 如果只是传数据可以无视name不调用
来用一个demo使用下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Text : MonoBehaviour {

    WebWork we = new WebWork();
    // Use this for initialization
    void Start () {
        we = transform.GetComponent<WebWork>();
        we.Init();       
        we.SendGet(EOPERATION.DownLoad,"chuanjianyinwei.mp4");
    }
    
    // Update is called once per frame
    void Update () {
      Debug.Log(we.GetProgress());
    }
}
image.png

打开exe开启一个临时资源服务器
记得设置端口号 把配置xml和要下载的文件放入


image.png

在主类把上面的地址粘贴过去


image.png

挂上脚本运行 进度条显示
image.png

资源服务器也有记录
image.png

打开项目文件夹也有


image.png

改了一下分发器只用实现接口 会根据反射自动初始化实例类 这样不用写那么多初始化代码了

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine.Networking;
using System.Reflection;
using System.Linq;

public enum EOPERATION
{
    LOGIN = 0,//登录
    REGISTER,//注册
    COLLEGELIST, //学院
    MAJORLIST, //专业
    CLASSLIST,//班级
    EXISTMAIL,//邮箱重复验证
    EXISTNUMBER, //学号重复验证
    GETPASSWORD,//忘记密码
    ADDSCORE,//添加成绩
    DownLoad,
}
public class CallBackUser
{
    public bool success;
    public string msg;
    public User obj;
}
/// <summary>
/// 分发器接口
/// </summary>
public interface IHander
{
    void RegisterMsg(Dictionary<EOPERATION, Action<string, DownloadHandler>> handers);
};
public class WebWork : MonoBehaviour
{
    Dictionary<EOPERATION, Action<string, DownloadHandler>> _handers = new Dictionary<EOPERATION, Action<string, DownloadHandler>>();
    bool isStartDownload;
    UnityWebRequest request;
    //根据协议号获取地址后缀
    Dictionary<EOPERATION, string> mURLs = new Dictionary<EOPERATION, string>{
        { EOPERATION.LOGIN,"webapi/login" },
        { EOPERATION.REGISTER,"webapi/register"},
        { EOPERATION.COLLEGELIST,"user/college/list_combo"},
        { EOPERATION.MAJORLIST,"user/major/list_combo"},
        { EOPERATION.CLASSLIST,"user/class/list_combo"},
        { EOPERATION.EXISTMAIL,"webapi/existemail"},
        { EOPERATION.EXISTNUMBER,"webapi/existnumber"},
        {EOPERATION.GETPASSWORD, "webapi/forget_pass"},
        {EOPERATION.ADDSCORE,"webapi/add_score"},
        {EOPERATION.DownLoad,"" }
    };

    private string ipAddress = "http://192.168.40.153:8000/";
    public object JsonConvert { get; private set; }

    //在这里注册消息返回后分发处理
    public void Init()
    {
        //返回我的解决方案中的所有程序集
        Type[] types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IHander))))
.ToArray();

        //相当于
        //public static IEnumerable<Type> GetType(Type interfaceType)
        //{
        //    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        //    {
        //        foreach (var type in assembly.GetTypes())
        //        {
        //            foreach (var t in type.GetInterfaces())
        //            {
        //                if (t == interfaceType)
        //                {
        //                    yield return type;
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //}
        foreach (var item in types)
        {
            IHander obj = (IHander)Activator.CreateInstance(item);
            obj.RegisterMsg(_handers);
        }
     
        DontDestroyOnLoad(this);
    }

    /// <summary>
    /// 传输数据
    /// </summary>
    /// <param name="dic"></param>
    /// <param name="op"></param>
    public void SendPost(EOPERATION op, Dictionary<string, string> dic)
    {
        //根据协议号获取完整路径
        string url = ipAddress + mURLs[op];
        StartCoroutine(Post(url, dic, op));
    }

    /// <summary>
    /// 获取数据
    /// </summary>
    /// <param name="op"></param>
    public void SendGet(EOPERATION op, string name = "")
    {
        string url = ipAddress + mURLs[op] + "/" + name;
        StartCoroutine(Get(url, op, name));
    }
    /// <summary>
    /// 获取下载进度
    /// </summary>
    /// <returns></returns>
    public float GetProgress()
    {
        if (request == null || !isStartDownload)
            return 0;
        return request.downloadProgress;
    }

    private IEnumerator Get(string url, EOPERATION op, string name)
    {
        if (!string.IsNullOrEmpty(url))
        {
            using (request = UnityWebRequest.Get(url))
            {
                isStartDownload = true;
                //设置超时 链接超时返回 且isNetworkError为true
                request.timeout = 30;
                yield return request.SendWebRequest();
                isStartDownload = false;
                //结果回传给具体实现
                if (request.isHttpError || request.isNetworkError)
                {
                    Debug.Log(request.error);
                }
                else
                {
                    _handers[op](name, request.downloadHandler);
                }
            };
        }
    }
    //private WWW http;
    private IEnumerator Post(string url, Dictionary<string, string> dic, EOPERATION op)
    {
        if (!string.IsNullOrEmpty(url))
        {
            WWWForm form = new WWWForm();

            foreach (var item in dic)
            {
                form.AddField(item.Key, item.Value);
            }
            using (request = UnityWebRequest.Post(url, form))
            {
                yield return request.SendWebRequest();
                //结果回传给具体实现
                if (request.isHttpError || request.isNetworkError)
                {
                    Debug.Log(request.error);
                }
                else
                {
                    _handers[op](name, request.downloadHandler);
                }
            }
        }
    }
}

然后是改了下读表

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine.Networking;
using System.Reflection;
using System.Linq;
using Newtonsoft.Json;
public enum EOPERATION
{
    LOGIN = 0,//登录
    REGISTER,//注册
    COLLEGELIST, //学院
    MAJORLIST, //专业
    CLASSLIST,//班级
    EXISTMAIL,//邮箱重复验证
    EXISTNUMBER, //学号重复验证
    GETPASSWORD,//忘记密码
    ADDSCORE,//添加成绩
    DownLoad,
}

/// <summary>
/// 分发器接口
/// </summary>
public interface IHander
{
    void RegisterMsg(Dictionary<EOPERATION, Action<TokenMsg>> handers);
}

public class UrlPath
{
    public EOPERATION operation;
    public string path;
}

public class WebWorkData
{
    public string ipAddress;
    public Dictionary<EOPERATION, string> urlPaths;
}

public struct TokenMsg
{
    public string name;
    public DownloadHandler hander;
}

public class WebWork
{
    Dictionary<EOPERATION, Action<TokenMsg>> _handers = new Dictionary<EOPERATION, Action<TokenMsg>>();
    public bool isStart { get; private set; }
    UnityWebRequest request;
    //根据协议号获取地址后缀
    WebWorkData webWorkData;

    //在这里注册消息返回后分发处理
    public void Init()
    {
        //返回我的解决方案中的所有程序集
        Type[] types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IHander))))
.ToArray();

        //相当于
        //public static IEnumerable<Type> GetType(Type interfaceType)
        //{
        //    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        //    {
        //        foreach (var type in assembly.GetTypes())
        //        {
        //            foreach (var t in type.GetInterfaces())
        //            {
        //                if (t == interfaceType)
        //                {
        //                    yield return type;
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //}
        foreach (var item in types)
        {
            IHander obj = (IHander)Activator.CreateInstance(item);
            obj.RegisterMsg(_handers);
        }


        //按Json格式序列化
        //WebWorkData web = new WebWorkData() { ipAddress = ipAddress, urlPaths = mURLs };
        //var json = JsonConvert.SerializeObject(web, Formatting.Indented);
        //FileTool.CreateFile(Application.streamingAssetsPath + "/WebData.json", json);

        var str = FileTool.BytesToStr(FileTool.ReadFile(Application.streamingAssetsPath + "/WebData.json"));
        webWorkData = JsonConvert.DeserializeObject<WebWorkData>(str);

    }

    string GetUrl(EOPERATION op, string name = "")
    {
        return webWorkData.ipAddress + webWorkData.urlPaths[op] + name;
    }

    /// <summary>
    /// 获取下载进度
    /// </summary>
    /// <returns></returns>
    public float GetProgress()
    {
        if (request == null || !isStart)
            throw new Exception(GetType() + "GetProgress()/request==null or !isStart");
        return request.downloadProgress;
    }


    public IEnumerator Get(EOPERATION op, string name)
    {
        string url = GetUrl(op, name);
        if (!string.IsNullOrEmpty(url))
        {
            using (request = UnityWebRequest.Get(url))
            {
                isStart = true;
                //设置超时 链接超时返回 且isNetworkError为true
                request.timeout = 30;
                yield return request.SendWebRequest();
                isStart = false;
                //结果回传给具体实现
                if (request.isHttpError || request.isNetworkError)
                {
                    Debug.Log(request.error);
                }
                else
                {
                    _handers[op](new TokenMsg { name = name, hander = request.downloadHandler });
                }
            };
        }
    }

    public IEnumerator Post(EOPERATION op, Dictionary<string, string> dic)
    {
        string url = GetUrl(op);
        if (!string.IsNullOrEmpty(url))
        {
            WWWForm form = new WWWForm();

            foreach (var item in dic)
            {
                form.AddField(item.Key, item.Value);
            }
            using (request = UnityWebRequest.Post(url, form))
            {
                isStart = true;
                request.timeout = 30;
                yield return request.SendWebRequest();
                isStart = false;
                //结果回传给具体实现
                if (request.isHttpError || request.isNetworkError)
                {
                    Debug.Log(request.error);
                }
                else
                {
                    _handers[op](new TokenMsg { hander = request.downloadHandler });
                }
            }
        }
    }
}

表是这个样子

{
  "ipAddress": "http://192.168.40.153:8000/",
  "urlPaths": {
    "LOGIN": "webapi/login/",
    "REGISTER": "webapi/register/",
    "COLLEGELIST": "user/college/list_combo/",
    "MAJORLIST": "user/major/list_combo/",
    "CLASSLIST": "user/class/list_combo/",
    "EXISTMAIL": "webapi/existemail/",
    "EXISTNUMBER": "webapi/existnumber/",
    "GETPASSWORD": "webapi/forget_pass/",
    "ADDSCORE": "webapi/add_score/",
    "DownLoad": "123/"
  }
}

然后分发集成了一个类,这样要添加属性改起来看起来不那么乱吧
地址
https://github.com/1004019267/NetWorkClient

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,874评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,102评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,676评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,911评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,937评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,935评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,860评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,660评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,113评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,363评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,506评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,238评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,861评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,486评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,674评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,513评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,426评论 2 352

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,094评论 1 32
  • 运行操作 CMD命令:开始->运行->键入cmd或command(在命令行里可以看到系统版本、文件系统版本) CM...
    小明yz阅读 2,756评论 0 8
  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 3,843评论 0 5
  • 个人学习批处理的初衷来源于实际工作;在某个迭代版本有个BS(安卓手游模拟器)大需求,从而在测试过程中就重复涉及到...
    Luckykailiu阅读 4,717评论 0 11
  • 命令简介 cmd是command的缩写.即命令行 。 虽然随着计算机产业的发展,Windows 操作系统的应用越来...
    Littleston阅读 3,317评论 0 12