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 string jsonDataPost;
    public string login_URL;
    void Start()
    {
        login_URL = "https://.....";//提供获取Token值的服务地址(很重要)
 
        jsonDataPost = "{ \"username\":\"159\", \"password\":\"hhhhhh\",\"clientType\": \"WEB\",\"pid\":\"01967189376\"}";//传JSON格式参数定义,具体根据提供的JOSN数据为准
        
        StartCoroutine(PostUrl(getData_URL, jsonGetData));
 
     
    }
 
    IEnumerator PostUrl(string url, string postData)
    {
        using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))//第二种写法此处注释
        {
             //UnityWebRequest webRequest = new UnityWebRequest(url, "POST");//第二种写法此处取消注释
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
            webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
            webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            webRequest.SetRequestHeader("Content-Type", "application/json");
 
            yield return webRequest.Send();
            if (webRequest.isNetworkError)
            {
                Debug.Log(webRequest.error);
            }
            else
            {
                TokenDataInfo tokenDataInfo = JsonMapper.ToObject<TokenDataInfo>(webRequest.downloadHandler.text);
                access_token = tokenDataInfo.access_token;
                refresh_token = tokenDataInfo.refresh_token;
                token_type = tokenDataInfo.token_type;
                authorization = token_type + " " + access_token;
 
                Debug.LogError(authorization);
                Debug.LogError(getData_URL);
                Debug.LogError(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}");
        }
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值