UnityWebRequest

引入

简介

UnityWebRequest 对象用于与 Web 服务器进行通信。 UnityWebRequest 处理 HTTP 与 Web 服务器进行通信的流程。其他对象 - 特别是 DownloadHandler 和 UploadHandler - 分别管理数据的下 和上传。

–来自unity文档

基本用法示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using system.Collections;
using UnityEngine;
using UnityEngine.Networking;

// 下载文本数据
//using 语法是为了确保这些对象在不再需要时能够及时释放资源。
Ienumertor DownloadText(string url)
{
    using(UnityWebRequest request = UnityWebRequest.Get(url))
    {
        yield return request.SendWebRequest();

        if(request.result == UnityWebRequest.Result.Success)
        {
            string text = request.downloadHandler.text;
            Debug.log("Download success: " + text);
        }
    }
}

// 下载文件并保存
IEnumerator DownloadFile(string url, string savePath)
{
    using(UnityWebRequest request = UnityWebRequest.Get(url))
    {
        request.downloadHandler = new DownloadHandlerFile(savePath);
        yield return request.SendWebRequest();
    }
}

// 上传表单数据
IEnumerator UploadData(string url, string data) 
{
    using(UnityWebRequest request = UnityWebRequest.Post(url, data)) 
    {
        byte[] jsonToSend = Encoding.UTF8.GetBytes(data);
        request.uploadHandler = new UploadHandlerRaw(jsonToSend);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        
        yield return request.SendWebRequest();
    }
}

常通过以下途径创建UnityWebRequest对象

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
//构造函数,method表示HTTP协议的GET, Post, PUT,不附加method和handler默认为GET method
public UnityWebRequest ();
public UnityWebRequest (string url);
public UnityWebRequest (string url, string method);
public UnityWebRequest (string url, string method, Networking.DownloadHandler downloadHandler, Networking.UploadHandler uploadHandler);

//通过静态函数返回
//这些函数可返回针对许多常见用例相应配置的 UnityWebRequest 对象。请参阅:Get、Post、Put、GetTexture。

public static Networking.UnityWebRequest Get (string uri);
//发送 HTTP HEAD 请求的 UnityWebRequest
public static Networking.UnityWebRequest Head (string uri);
//将原始数据上传到远程服务器的 UnityWebRequest
public static Networking.UnityWebRequest Post (string uri, string postData);
//向 uri 传输 bodyData的 UnityWebRequest
public static Networking.UnityWebRequest Put (string uri, byte[] bodyData);
public static Networking.UnityWebRequest Put (string uri, string bodyData);

可以发现UnityWebRequest包含一些重要变量,常用的是downloadHandleruploadHandler类的引用,定义如何处理从远程服务器接收的 HTTP 响应体数据。
还有之后的request.SendWebRequest()向url发送请求的方法。这里一般用yield return等待请求完成,防止阻塞主线程。

Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计