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> _handers = new Dictionary>();
    private string filepath;
    bool isStartDownload;
    UnityWebRequest request;
    //根据协议号获取地址后缀
    Dictionary mURLs = new Dictionary{
        { 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);
    }
    /// 
    /// 传输数据
    /// 
    /// 
    /// 
    public void SendPost(EOPERATION op, Dictionary dic)
    {
        //根据协议号获取完整路径
        string url = ipAddress + mURLs[op];
        StartCoroutine(Post(url, dic, op));
    }

    /// 
    /// 获取数据
    /// 
    /// 
    public void SendGet(EOPERATION op, string name = "")
    {
        string url = ipAddress + mURLs[op] + "/" + name;
        StartCoroutine(Get(url, op, name));
    }
    /// 
    /// 获取下载进度
    /// 
    /// 
    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 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
{
    /// 
    /// 创建文件
    /// 
   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> 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(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> handers)
 {

}

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

更多unity2018的功能介绍请到paws3d爪爪学院查找。链接https://www.paws3d.com/,也可以加入unity学习讨论群935714213

近期更有资深开发人士直播分享unity开发经验,详情请进入官网或加入QQ群了解
 

你可能感兴趣的:(unity2018)