Unity UnityWebRequest使用

 下载:

  //进度条
    public Image jindu;
    public Text jindu_Progress;

    /// <summary>
    /// 下载
    /// </summary>
    /// <param name="url">下载的地址</param>
    /// <returns></returns>
    IEnumerator Download()
    {
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url);
        request.SendWebRequest();
        if (request.isHttpError || request.isNetworkError)
        {
            print("当前的下载发生错误" + request.error);
            yield break;
        }
        while (!request.isDone)
        {
            print("当前的下载进度为:" + request.downloadProgress);
            jindu.fillAmount = request.downloadProgress;
            jindu_Progress.text = request.downloadProgress.ToString("P0");
            yield return 0;
        }
        if (request.isDone)
        {
            jindu.fillAmount = 1;
            jindu_Progress.text = "100%";
            //处理下载的文件
            AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
            //GameObject obj = ab.LoadAsset<GameObject>("wall");
            Object[] objs = ab.LoadAllAssets();
            foreach (var item in objs)
            {
                GameObject obj = Instantiate(item) as GameObject;
                obj.name = "Model";
            }
            Invoke("LoadMainSCene", 1f);
        }
    }

上传

 void Start()
    {
        WWWForm form = new WWWForm();
        form.AddField("aaa", "123");  //需要提交的数据也由后端提供
        form.AddField("password", "123");
        StartCoroutine(SendPost(url, form));
    }



    IEnumerator SendPost(string _url, WWWForm _wForm)

    {
        WWW postData = new WWW(_url, _wForm);
        yield return postData;
        if (postData.error != null)
        {
            Debug.Log(postData.error);
        }

        else
        {

            Debug.Log("发送成功...");
            string str = postData.text;

            Debug.Log(str);


            //JsonData data = JsonMapper.ToObject(str);
            //print(data["msg"]);
            //print(data["status"]); //由后端提供json数据
        }
    }

using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
//UnityWebRequest的命名空间
using UnityEngine.Networking;

public class GameApp : MonoBehaviour
{
    string url = "http://127.0.0.1";
    string url_Remote = "http://1135416341576";
    string port = "6080";
    string port_Remote = "6080";
    string userName = "你好 ";
    string password = "abc123";
    public void EnterGame()
    {
        //this.StartCoroutine(ReadResVersion());//获取版本号
        // this.StartCoroutine(UploadResFile());//上传文件到服务器
        //this.StartCoroutine(DownLoadResFile());//下载文件  热更用


        //this.StartCoroutine(GetUploadData());//发送数据信息
        StartCoroutine(Upload());
        //StartCoroutine(LoginReq());

    }

    IEnumerator UploadResFile()//上传文件到服务器
    {
        string fileName = Application.persistentDataPath + "/VSCodeUserSetup-x64-1.76.1.exe";
        byte[] body = GameUtils.SafeReadAllBytes(fileName);
        Debug.Log(body.Length);
        UnityWebRequest req = UnityWebRequest.Put("http://127.0.0.1:6080/UploadFile", body);
        Debug.Log(req.downloadProgress);
        yield return req.SendWebRequest();
        Debug.Log(req.downloadHandler.text);//打印返回值
    }



    IEnumerator DownLoadResFile()//从服务器下载文件
    {
        //string url = "http://127.0.0.1:6080/Sounds/许巍 - 蓝莲花.mp3";
        string url = "http://127.0.0.1:6080/AppAssets/VSCodeUserSetup-x64-1.76.1.exe";//要下载的地址
        UnityWebRequest request = UnityWebRequest.Get(url);
        request.SendWebRequest();
        while (!request.isDone)
        {
            Debug.Log("下载进度" + request.downloadProgress);
            yield return null;
        }

        if (request.isDone)
        {
            //my_Slider.value = 1;
            //将下载的文件写入
            //using (FileStream fs = new FileStream(Application.streamingAssetsPath + "/Test.MP4", FileMode.Create))
            //{
            //    byte[] data = request.downloadHandler.data;
            //    fs.Write(data, 0, data.Length);
            //}
        }


        byte[] body = request.downloadHandler.data;
        //把文件保存到本地
        string fileName = Application.persistentDataPath + "/VSCodeUserSetup-x64-1.76.1.exe";
        //string fileName = Application.streamingAssetsPath + "/VSCodeUserSetup-x64-1.76.1.exe";
        Debug.Log(fileName);
        Debug.Log("下载完成");
        GameUtils.SafeWriteAllBytes(fileName, body);
        yield break;
    }


    IEnumerator ReadResVersion()//从服务器读取版本号
    {
        //UnityWebRequest unityWebRequest = UnityWebRequest.Get("http://127.0.0.1:6080/version.txt");
        UnityWebRequest unityWebRequest = UnityWebRequest.Get("http://152161653.93:6080/version.txt");
        yield return unityWebRequest.SendWebRequest();
        Debug.Log(unityWebRequest.downloadHandler.text);
        yield break;
    }

    IEnumerator GetBaidu()
    {
        //构建UnityWebRequest协议的请求
        UnityWebRequest request = UnityWebRequest.Get("http://www.baidu.com/");

        yield return request.SendWebRequest();//像服务器发送请求,采用携程等待不卡住,然后主线程继续做别的,请求返回后

        Debug.Log("链接成功");

        Debug.Log(request.downloadHandler.text);
        yield break;
    }


    IEnumerator GetUploadData()
    {
        print("你好");
        //构建UnityWebRequest协议的请求                                               ?就是query 服务器查询问好后面的内容 
        //UnityWebRequest req = UnityWebRequest.Get("http://127.0.0.1:6080/uploadData?uname=张三&upwd=123456");
        UnityWebRequest request = UnityWebRequest.Get(url_Remote + ":" + port_Remote + "/uploadData?用户名=" + userName + "&密码=" + password);
        //UnityWebRequest request = UnityWebRequest.Get("http://123.57.68.76:6080/uploadData?uname=张三&upwd=123456");

        yield return request.SendWebRequest();//像服务器发送请求,采用携程等待不卡住,然后主线程继续做别的,请求返回后

        Debug.Log("链接成功");

        Debug.Log(request.downloadHandler.text);//打印服务器返回信息
        yield break;
    }


    IEnumerator Upload()
    {
        WWWForm form = new WWWForm();
        form.AddField("myField", "myData");
        //UnityWebRequest www = UnityWebRequest.Post("https://www.my-server.com/myform", form);
        UnityWebRequest www = UnityWebRequest.Post("http://1231561564:6080/postUploadData", form);
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("数据发送成功 complete!");
            Debug.Log(www.downloadHandler.text);

        }
    }


    IEnumerator LoginReq()
    {
        WWWForm www = new WWWForm();
        www.AddField("username", "aaa");
        www.AddField("password", password);
        www.headers["Content-Type"] = "application/json";
        UnityWebRequest request = UnityWebRequest.Post("https://www.my-server.com/myform", www);
        yield return request.SendWebRequest();
        if (request.isDone && !request.isHttpError && !request.isNetworkError && request.responseCode.ToString() == "200")
        {

            print(request.downloadHandler.text);
            //JsonData data = JsonMapper.ToObject(request.downloadHandler.text);
        }

    }

}

2023.9.8补充:

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

public class GameUtils : MonoBehaviour
{
    public static bool SafeWriteAllBytes(string outfile, byte[] outBytes)
    {
        if (string.IsNullOrEmpty(outfile))
        {
            return false;
        }
        if (File.Exists(outfile))
        {
            File.SetAttributes(outfile, FileAttributes.Normal);
        }
        File.WriteAllBytes(outfile, outBytes);
        return true;
    }



    public static byte[] SafeReadAllBytes(string fileName)
    {
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        try
        {
            byte[] buffur = new byte[fs.Length];
            fs.Read(buffur, 0, (int)fs.Length);

            return buffur;
        }
        catch (Exception ex)
        {
            //MessageBoxHelper.ShowPrompt(ex.Message);
            return null;
        }
        finally
        {
            if (fs != null)
            {

                //关闭资源
                fs.Close();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38513810/article/details/130646218