Unity C# 网络学习(九)——WWWFrom

本文介绍了在Unity中如何利用WWWForm类进行POST方式的数据上传,包括添加字段和二进制数据的方法。通过示例代码展示了异步上传过程,并提供了与后端交互的函数模板。此外,还给出了发送数据的示例,演示了如何解析返回的二进制消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Unity C# 网络学习(九)——WWWFrom

  • 如果想使用WWW上传数据时,就需要配合WWWFrom类进行使用了
  • 它主要用到的请求类型是Post
  • 使用WWWFrom上传数据一般需要配合后端程序制定上传规则

一.WWWFrom类

1.WWWFrom类的常用方法

        WWWForm wwwForm = new WWWForm();
        //1.添加二进制数据
        wwwForm.AddBinaryData("xxx", new byte[10]);
        //2.添加字段
        wwwForm.AddField("name", "zzs", Encoding.UTF8);

2.WWW结合WWWFrom对象来异步上传数据

    private IEnumerator UpLoadData()
    {
        WWWForm data = new WWWForm();
        data.AddField("Name", "zzs", Encoding.UTF8);
        data.AddField("Age", 18);
        data.AddBinaryData("file",File.ReadAllBytes(Application.streamingAssetsPath +"/test.jpg"),"myTest.jpg","application/octet-stream");
        
        WWW www = new WWW("http://192.168.1.103:8080/Http_Server/", data);
        yield return www;
        if (www.error == null && www.isDone)
        {
            Debug.Log("上传成功!");
        }
        else
        {
            Debug.Log("上传失败!" + www.error);
        }
    }

二.WWWFrom 发送数据

    public void SendMsg<T>(MsgBase msg,Action<T> action) where T: MsgBase
    {
        StartCoroutine(SendMsgAsync(msg,action));
    }
    private IEnumerator SendMsgAsync<T>(MsgBase msg,Action<T> action)where T: MsgBase
    {
        WWWForm wwwForm = new WWWForm();
        wwwForm.AddBinaryData("Msg",msg.ToArray());
        WWW www = new WWW(RootUrl,wwwForm);
        yield return www;
        if (www.error == null)
        {
            int index = 0;
            int msgId = BitConverter.ToInt32(www.bytes, 0);
            index += 4;
            int length = BitConverter.ToInt32(www.bytes, index);
            index += 4;
            MsgBase msgBase = null;
            switch (msgId)
            {
                case 1001:
                    msgBase = new PlayerMsg();
                    msgBase.Reading(www.bytes, index);
                    break;
            }

            if (msgBase != null)
            {
                action?.Invoke(msgBase as T);
            }
        }
        else
        {
            Debug.Log("发消息出现问题:"+www.error);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值