Unity UnityWebRequest使用方法

简介

UnityWebRequest 提供了一个模块化系统,用于构成 HTTP 请求和处理 HTTP 响应。

结构

  • UploadHandler: 处理数据到服务器的传输
  • DownloadHandler: 处理从服务器接收的数据的接收、缓冲和后处理
  • UnityWebRequest: 管理上面两个对象

详情

一、和WWW的区别

WWW和UnityWebRequest都用于处理Http请求,UnityWebRequest是后面出的用于替代WWW的模块。相比于WWW,UnityWebRequest支持设置timeout超时时间,支持断点续传,在一些复杂操作上也有更好的表现。

二、构造方法

  • public UnityWebRequest()
  • public UnityWebRequest(string url)
  • public UnityWebRequest(Uri uri)
  • public UnityWebRequest(string url, string method)
  • public UnityWebRequest(Uri uri, string method)
  • public UnityWebRequest(string url,string method,DownloadHandler downloadHandler,UploadHandler uploadHandler)
  • public UnityWebRequest(Uri uri,string method,DownloadHandler downloadHandler,UploadHandler uploadHandler)

三、封装的构造方法

  • UnityWebRequest.Get(string uri)
  • UnityWebRequest.Post(string uri, WWWForm formData)
  • UnityWebRequest.Delete(string uri)
  • UnityWebRequest.Head(string uri)
  • UnityWebRequest.Put(string uri, string bodyData)

上面这些方法是对构造方法的封装,上面列举的方法,它们自己还有其他的重载方法。
比如Get()还有UnityWebRequest.Get(Uri uri)重载方法,不过主要是这5个构造类型。
推荐使用这些封装的方法来构造。

四、使用举例

Get()

    private IEnumerator Get()
    {
    
    
        var request = UnityWebRequest.Get("http://www.baidu.com");
        yield return request.SendWebRequest();
        if (request.isHttpError || request.isNetworkError)
        {
    
    
            Debug.LogError(request.error);
        }
        else
        {
    
    
            Debug.Log(request.downloadHandler.text);
        }
    }

Post()

    private IEnumerator Post()
    {
    
    
    	//这里使用WWWForm来构建键值对。和WWW的使用是一致的
        WWWForm form = new WWWForm();
        form.AddField("key","value");
        UnityWebRequest webRequest = UnityWebRequest.Post("http://www.baidu.com",form);
        
        yield return webRequest.SendWebRequest();
        
        if (webRequest.isHttpError || webRequest.isNetworkError)
        {
    
    
            Debug.LogError(webRequest.error);
        }
        else
        {
    
    
            Debug.Log(webRequest.downloadHandler.text);
        }
    }

读取过程中显示进度

显示进度要换种写法,如下

    private IEnumerator GetShowProgress()
    {
    
    
        UnityWebRequest request = UnityWebRequest.Get("www.baidu.com");
        request.SendWebRequest();
        while (!request.isDone)
        {
    
    
            Debug.Log($"{
      
      GetType()} progress:{
      
      request.downloadProgress}");
            yield return null;
        }
		
		Debug.Log($"{
      
      GetType()} progress:{
      
      request.downloadProgress}");

        if (request.isNetworkError || request.isHttpError)
        {
    
    
            Debug.LogError($"{
      
      GetType()} error:{
      
      request.error}");
        }
        else
        {
    
    
            Debug.Log($"{
      
      GetType()} text:{
      
      request.downloadHandler.text}");
            Debug.Log($"{
      
      GetType()} bytes.length:{
      
      request.downloadHandler.data.Length}");
        }
    }

五、加载图片

使用UnityWebRequestTexture.GetTexture()快捷获取网络/本地图片

		 	 // 从本地文件系统中读取图片数据
            string url = photoPath;
            if (Application.platform == RuntimePlatform.Android)
            {
            	//如果是从android机器上的路径加载,添加file://前缀
                url = "file://" + photoPath;
            }


            var request = UnityWebRequestTexture.GetTexture(url);
            yield return request.SendWebRequest();
            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.Log("Failed to download image: " + request.error);
                yield break;
            }
        
            // 将下载的纹理设置为主纹理
            var texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
            if (texture == null)
            {
                Debug.Log("Failed to download image data");
                yield break;
            }
            //赋给RawImage
            rawImage.texture = texture;
           
           //赋给Image       
            Sprite sp = Sprite.Create(self.tex, new Rect(0, 0, self.tex.width, self.tex.height), Vector2.zero);//先转成Sprite
			image.sprite = sp;

Guess you like

Origin blog.csdn.net/aaa27987/article/details/121953515