【Unity网络编程知识】Unity的 UnityWebRequest相关类学习

1、UnityWebRequest类介绍

UnityWebRequest是一个unity提供的一个模块化的系统类,用于构成HTTP请求和处理HTTP响应,它主要目标是让unity游戏和Web服务端进行交互,它将之前WWW的相关功能都集成在了其中,所以新版本中都建议使用unityWebRequest类来代替WWW类,它在使用上和WWW很类似,主要的区别就是unityWebRequest把下载下来的数据处理单独提取出来了,我们可以根据自己的需求选择对应的数据处理对象来获取数据。

注意:

  • UnityWebRequest和www一样,需要配合协同程序使用
  • UnityWebRequest和www一样,支持http、ftp、file协议下载或加载资源
  • UnityWebRequest能够上传文件到HTTP资源服务器

2、UnityWebRequest常规操作获取数据

2.1 使用Get请求获取文本或二进制数据,UnityWebRequest.Get

cs 复制代码
    StartCoroutine(LoadText());

    IEnumerator LoadText()
    {
        //UnityWebRequest req = UnityWebRequest.Get("ftp://127.0.0.1/xxx.png");
        //UnityWebRequest req = UnityWebRequest.Get("file://" + Application.streamingAssetsPath + "/test.png");
        UnityWebRequest req = UnityWebRequest.Get("https://apis.tianapi.com/esports/index?key=569f5d47f6840feced4db412448e44f5&num=10");

        yield return req.SendWebRequest();

        //如果处理成功 结果就是成功枚举
        if(req.result == UnityWebRequest.Result.Success )
        {
            //文本 字符串
            print(req.downloadHandler.text);
            //字节数组
            byte[] bytes = req.downloadHandler.data;
            print(bytes.Length);
        }
        else
        {
            print("获取失败:" + req.result + req.error + req.responseCode);
        }
    }

2.2 使用Get请求获取纹理数据,UnityWebRequestTexture.GetTexture

cs 复制代码
    StartCoroutine(LoadTexture());

    IEnumerator LoadTexture()
    {
        UnityWebRequest req = UnityWebRequestTexture.GetTexture("https://qcloud.dpfile.com/pc/DfcPF0Dzu9D9Qd9Wm3_qdklLIicjzbTkXVl-rKrD1BAXyPEkpUqfdIUZwCbbB1Xz.jpg");

        yield return req.SendWebRequest();

        if(req.result == UnityWebRequest.Result.Success)
        {
            //(req.downloadHandler as DownloadHandlerTexture).texture
            //DownloadHandlerTexture.GetContent(req);

            image.texture = DownloadHandlerTexture.GetContent(req);
        }
        else
        {
            Debug.LogError("获取失败" + req.error + req.result + req.responseCode);
        }

    }

2.3 使用Get请求获取AB包数据,UnityWebRequestAssetBundle.GetAssetBundle

cs 复制代码
    IEnumerator LoadAB()
    {
        UnityWebRequest req = UnityWebRequestAssetBundle.GetAssetBundle("http://192.168.1.25:8000/HttpServer/lua");

        req.SendWebRequest();

        while(!req.isDone)
        {
            print(req.downloadProgress);
            print(req.downloadedBytes);

            yield return 0;
        }

        //yield return req.SendWebRequest();

        if(req.result == UnityWebRequest.Result.Success)
        {
            //AssetBundle ab = (req.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
            AssetBundle ab = DownloadHandlerAssetBundle.GetContent(req);

            print(ab.name);
        }
        else
        {
            Debug.LogError("获取失败" + req.error + req.result + req.responseCode);
        }
    }

3、UnityWebRequest常规操作上传数据

3.1 上传相关数据类,IMuItipartFormSection接口

cs 复制代码
        //IMuItipartFormSection
        //数据相关类都继承该接口
        //我们可以用父类装子类

        List<IMultipartFormSection> datalist = new List<IMultipartFormSection>();

1)MultipartFormDataSection

cs 复制代码
        //1.二进制字节数组
        datalist.Add(new MultipartFormDataSection(Encoding.UTF8.GetBytes("djadjad")));
        //2.字符串
        datalist.Add(new MultipartFormDataSection("dsdadad"));
        //3.参数名,参数值(字节数组,字符串),编码类型,资源类型(常用)
        datalist.Add(new MultipartFormDataSection("Name", "ZTT", Encoding.UTF8, "text/..."));
        datalist.Add(new MultipartFormDataSection("Msg", new byte[1024], "application/..."));

2)MultipartFormFileSection

cs 复制代码
        //1.字节数组
        datalist.Add(new MultipartFormFileSection(File.ReadAllBytes(Application.streamingAssetsPath + "/test.png")));
        //2.文件名,字节数组(常用)
        datalist.Add(new MultipartFormFileSection("FileName.png", File.ReadAllBytes(Application.streamingAssetsPath + "/test.png")));
        //3.字符串数据,文件名(常用)
        datalist.Add(new MultipartFormFileSection("123", "test.txt"));
        //4.字符串数据,编码格式,文件名(常用)
        datalist.Add(new MultipartFormFileSection("fdfds", Encoding.UTF8, "test.txt"));
        //5.表单名,字节数组,文件名,文件类型
        datalist.Add(new MultipartFormFileSection("file", new byte[1024], "test.txt", ""));
        //6.表单名,字符串数据,编码格式,文件名
        datalist.Add(new MultipartFormFileSection("file", "dada", Encoding.UTF8, "test.txt"));

3.2 Post发送请求

cs 复制代码
    StartCoroutine(UpLoad());

    IEnumerator UpLoad()
    {
        //准备上传的数据
        List<IMultipartFormSection> data = new List<IMultipartFormSection>();

        //键值对相关的 信息 字段数据
        data.Add(new MultipartFormDataSection("Name", "ZTT"));
        //PlayerMsg msg = new PlayerMsg();
        //data.Add(new MultipartFormDataSection("Msg", msg.Writing()));
        //添加一些文件上传文件
        //传二进制文件
        data.Add(new MultipartFormFileSection("test.png", File.ReadAllBytes(Application.streamingAssetsPath + "/test.png")));
        //传文本文件
        data.Add(new MultipartFormFileSection("文件字符串内容", "test2.png"));

        UnityWebRequest req = UnityWebRequest.Post("http://192.168.1.25:8000/HttpServer/", data);

        req.SendWebRequest();

        while(!req.isDone)
        {
            print(req.uploadProgress);
            print(req.uploadedBytes);
            yield return null;
        }

        print(req.uploadProgress);
        print(req.uploadedBytes);

        if(req.result == UnityWebRequest.Result.Success)
        {
            print("上传成功");
            //req.downloadHandler.data
        }

    }

3. 3 Put上传请求

cs 复制代码
    StartCoroutine(UpLoadPut());

    IEnumerator UpLoadPut()
    {
        UnityWebRequest req = UnityWebRequest.Put("http://192.168.1.25:8000/HttpServer/", File.ReadAllBytes(Application.streamingAssetsPath + "/test.png"));

        yield return req.SendWebRequest();

        if(req.result == UnityWebRequest.Result.Success)
        {
            print("上传成功");
        }
        else
        {

        }

    }

4、 UnityWebRequest类的常用方法和变量

1)构造函数

cs 复制代码
UnityWebRequest req = new UnityWebRequest();

2)请求地址

cs 复制代码
req.url = "服务器地址";

3)请求类型

cs 复制代码
req.method = UnityWebRequest.kHttpVerbGET;

4)上传、下载的进度

cs 复制代码
req.downloadProgress
req.uploadProgress

5)超时设置

cs 复制代码
req.timeout = 2000;

6)上传、下载的字节数

cs 复制代码
req.downloadedBytes
req.uploadedBytes

7)重定向次数设置为0表示不进行重定向可以设置次数

cs 复制代码
req.redirectLimit = 2;

8)状态码、结果、错误内容

cs 复制代码
req.responseCode
req.result
req.error

9)下载、上传处理对象

cs 复制代码
req.downloadHandler
req.uploadHandler

5、UnityWebRequest高级操作获取数据

4.1 发送Get请求

cs 复制代码
        // 关键类:
        //1.DownloadHandlerBuffer       用于简单的数据存储,得到对应的2进制数据。
        //2.DownloadHandlerFile         用于下载文件并将文件保存到磁盘(内存占用少)。
        //3.DownloadHand1erTexture      用于下载图像。
        //4.DownloadHandlerAssetBundle  用于提取AssetBundle。
        //5.DownloadHandlerAudioC1ip    用于下载音频文件。

        StartCoroutine(DownLoadTex());

    IEnumerator DownLoadTex()
    {
        UnityWebRequest req = new UnityWebRequest("https://qcloud.dpfile.com/pc/DfcPF0Dzu9D9Qd9Wm3_qdklLIicjzbTkXVl-rKrD1BAXyPEkpUqfdIUZwCbbB1Xz.jpg", UnityWebRequest.kHttpVerbGET);

        //1.DownloadHandlerBuffer
        //DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer();
        //req.downloadHandler = downloadHandlerBuffer;

        //2.DownloadHandlerFile
        //print(Application.persistentDataPath);
        //req.downloadHandler = new DownloadHandlerFile(Application.persistentDataPath + "/downloadFile.jpg");

        //3.DownloadHand1erTexture
        DownloadHandlerTexture textureDownLoadHandle = new DownloadHandlerTexture();
        req.downloadHandler = textureDownLoadHandle;

        yield return req.SendWebRequest();

        if(req.result == UnityWebRequest.Result.Success)
        {
            //获取字节数组
            //downloadHandlerBuffer.data;

            //textureDownLoadHandle.texture
            image.texture = textureDownLoadHandle.texture;
        }
        else
        {
            print("获取数据失败" + req.result + req.error + req.responseCode);
        }
    }

4.2 自定义实现获取数据DownloadHandler相关类

步骤一、继承DownloadHandlerScript,实现CustomDownLoadFileHandle 类

cs 复制代码
public class CustomDownLoadFileHandle : DownloadHandlerScript
{
    //用于保存 本地存储时的路径
    private string savePath;
    //用于缓存收到的数据的容器
    private byte[] cacheBytes;
    //当前已收到的数据长度
    private int index = 0;

    public CustomDownLoadFileHandle():base()
    {

    }

    public CustomDownLoadFileHandle(byte[] bytes) : base(bytes)
    {

    }

    public CustomDownLoadFileHandle(string path) : base()
    {
        savePath = path;
    }


    protected override byte[] GetData()
    {
        //return base.GetData();
        return cacheBytes;
    }

    /// <summary>
    /// 从网络收到数据后 每帧会调用的方法
    /// </summary>
    /// <param name="data"></param>
    /// <param name="dataLength"></param>
    /// <returns></returns>
    protected override bool ReceiveData(byte[] data, int dataLength)
    {
        //return base.ReceiveData(data, dataLength);
        Debug.Log("收到数据长度:" + data.Length);
        Debug.Log("收到数据长度dataLength:" + dataLength);
        data.CopyTo(cacheBytes, index);
        index += dataLength;
        return true;
    }

    /// <summary>
    /// 从服务器收到 Content-Length标头时 会调用
    /// </summary>
    /// <param name="contentLength"></param>
    protected override void ReceiveContentLengthHeader(ulong contentLength)
    {
        //base.ReceiveContentLengthHeader(contentLength);
        Debug.Log("收到数据长度:" +  contentLength);

        //根据收到的标头 决定字节数组容器的大小
        cacheBytes = new byte[contentLength];
    }

    /// <summary>
    /// 当消息收完了 会自动调用的方法
    /// </summary>
    protected override void CompleteContent()
    {
        //base.CompleteContent();
        Debug.Log("消息收完");
        //把收到的字节数组 进行自定义处理 我们在这 处理成 存储到本地
        File.WriteAllBytes(savePath, cacheBytes);
    }

}

步骤二、使用自定义获取数据DownloadHandler相关类

cs 复制代码
    StartCoroutine(DownLoadCustomHandle());

    IEnumerator DownLoadCustomHandle()
    {
        UnityWebRequest req = new UnityWebRequest("https://qcloud.dpfile.com/pc/DfcPF0Dzu9D9Qd9Wm3_qdklLIicjzbTkXVl-rKrD1BAXyPEkpUqfdIUZwCbbB1Xz.jpg", UnityWebRequest.kHttpVerbGET);

        //使用自定义的下载处理对象 来处理获取到的 2进制字节数组
        print(Application.persistentDataPath);
        req.downloadHandler = new CustomDownLoadFileHandle(Application.persistentDataPath + "/CustomHandle.jpg");

        yield return req.SendWebRequest();

        if(req.result == UnityWebRequest.Result.Success)
        {
            print("存储本地成功");
        }
        else
        {
            print("获取数据失败" + req.result + req.error + req.responseCode);
        }

    }

6、UnityWebRequest高级操作上传数据

6.1 发送Post请求

cs 复制代码
        // 注意:
        //由于UnityWebRequest类的常用操作中
        //上传数据相关内容已经封装的很好了
        //我们可以很方便的上传参数和文件
        //我们使用常用操作已经能够满足常用需求了
        //所以以下内容主要做了解

        //UploadHandler相关类
        //1.UploadHandlerRaw    用于上传字节数组
        StartCoroutine(UpLoad());
        //2.UploadHandlerFile   用于上传文件

    IEnumerator UpLoad()
    {
        UnityWebRequest req = new UnityWebRequest("http://192.168.1.25:8000/HttpServer/", UnityWebRequest.kHttpVerbPOST);

        //1.UploadHandlerRaw    用于上传字节数组
        //byte[] bytes = Encoding.UTF8.GetBytes("13131344");
        //req.uploadHandler = new UploadHandlerRaw(bytes);
        //req.uploadHandler.contentType = "类型/细分类型";

        //2.UploadHandlerFile   用于上传文件
        req.uploadHandler = new UploadHandlerFile(Application.streamingAssetsPath + "/test.png");

        yield return req.SendWebRequest();

        print(req.result);

    }
相关推荐
Da Da 泓6 分钟前
[项目] --- 基于websocket的网页五子棋(可多用户)
网络·websocket·网络协议·多线程·项目
lazy H13 分钟前
【计算机网络】第 2 篇:一条数据如何穿过网络?彻底理解数据封装与解封装
网络·经验分享·后端·学习·计算机网络
一木 之林27 分钟前
微信小程序开发全攻略·文章版|05 路由·交互·网络与音乐播放器实战
网络·微信小程序·小程序·交互
yunlaodacom1 小时前
华为云国际站服务代理商:BMS数据库延迟突然升高?磁盘I/O、网络与CPU排查方法
网络·数据库·华为云
张宇Joaquin1 小时前
自研SP600系列网卡驱动跟麒麟V10 SP3 2403配套关系
linux·运维·网络
睡一觉就好了。2 小时前
Cookie与Session
网络
步行cgn2 小时前
HTTP 常用请求方法详解
网络·网络协议·http
mengge.cloud2 小时前
1019Namespace ,Contexts ,Kubernetes Pod
运维·服务器·网络·云原生·容器·kubernetes·云计算
艾iYYY2 小时前
【无标题】
linux·开发语言·网络·操作系统
QZ166560951592 小时前
可视化易用·低误报率·跨区域部署:知源-AI数据分类分级系统在金融行业的落地实践
大数据·网络·安全·网络安全