【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

    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

    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

    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接口

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

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

1)MultipartFormDataSection

        //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

        //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发送请求

 

    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上传请求

    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)构造函数

UnityWebRequest req = new UnityWebRequest();

2)请求地址

req.url = "服务器地址";

3)请求类型

req.method = UnityWebRequest.kHttpVerbGET;

4)上传、下载的进度

req.downloadProgress
req.uploadProgress

5)超时设置

req.timeout = 2000;

6)上传、下载的字节数

req.downloadedBytes
req.uploadedBytes

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

req.redirectLimit = 2;

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

req.responseCode
req.result
req.error

9)下载、上传处理对象

req.downloadHandler
req.uploadHandler

5、UnityWebRequest高级操作获取数据

4.1 发送Get请求

        // 关键类:
        //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 类

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相关类

    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请求

        // 注意:
        //由于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);

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值