Unity的http访问工具UnityWebRequest使用

http访问工具类

unity 原来有个http访问的工具类WWW,参考http://www.superzhan.cn/?p=112。在新版本的Unity中,推出了新的工具类UnityWebRequest,可以代替原来的WWW类。

简单的Get访问

UnityWebRequest包含多个静态方法,可以创建一个UnityWebRequest对象,调用SendWebRequest正式发送请求。在协程返回结果后,需要判断是否有错误,再做处理。

using System.Collections;
using System.Collections.Generic;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;
public class NewBehaviourScript : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(GetRequest());
    }

    public IEnumerator GetRequest()
    {
        string url = "https://www.baidu.com/";
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {

            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
            }
            else
            {
                Debug.Log(webRequest.downloadHandler.text);
            }
        }
    }
}

Http post访问

项目中post访问提交的数据都是json格式的,这里需要对提交的数据uploadHandler做处理,把提交的数据抓换为byte数组。 如果提交的是form表单,可以参考官方文档。

public IEnumerator PostRequest(string methodName, string jsonString, Action<string> callback)
    {
        string url = baseUrl + methodName;
        using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
            webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();

            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                if (callback != null)
                {
                    callback(null);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(webRequest.downloadHandler.text);
                }
            }
        }
    }

http header设置

访问http接口时,考虑到安全方面的问题,可以在提交的数据里面加上一个key字符串,用于身份验证。

这个key字符串可以放到http 的 header中。

设置header方法

 webRequest.SetRequestHeader(Key, Value);

完整工具代码封装

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Networking;
using System.Text;

/// <summary>
/// Http Request SDK 
/// </summary>
public class HttpTool : MonoBehaviour
{

    private static HttpTool _instacne = null;
    public string baseUrl = "https://127.0.0.1:3000/";
    public string sKey = "zoo_visit_key";

    Dictionary<string, string> requestHeader = new Dictionary<string, string>();  //  header
    public static HttpTool Instance
    {
        get
        {
            if (_instacne == null)
            {
                Debug.LogError("Awake error");
            }
            return _instacne;
        }
    }

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        HttpTool._instacne = gameObject.GetComponent<HttpTool>();

         //http header 的内容
        requestHeader.Add("Content-Type", "application/json");
        requestHeader.Add("sKey", sKey);

    }

    public void Get(string methodName, Action<string> callback)
    {
        StartCoroutine(GetRequest(methodName, callback));
    }
    public IEnumerator GetRequest(string methodName, Action<string> callback)
    {
        string url = baseUrl + methodName;
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            //设置header
            foreach (var v in requestHeader)
            {
                webRequest.SetRequestHeader(v.Key, v.Value);
            }
            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                if (callback != null)
                {
                    callback(null);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(webRequest.downloadHandler.text);
                }
            }
        }
    }

   //jsonString 为json字符串,post提交的数据包为json
    public void Post(string methodName,string jsonString, Action<string> callback)
    {
        StartCoroutine(PostRequest(methodName,jsonString,callback));
    }
    public IEnumerator PostRequest(string methodName, string jsonString, Action<string> callback)
    {
        string url = baseUrl + methodName;
       // Debug.Log(string.Format("url:{0} postData:{1}",url,jsonString));
        using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
            webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();

            foreach (var v in requestHeader)
            {
                webRequest.SetRequestHeader(v.Key, v.Value);
            }
            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                if (callback != null)
                {
                    callback(null);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(webRequest.downloadHandler.text);
                }
            }
        }
    }
}

参考

更多的使用方法,可以参考官方文档。
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/Networking.UnityWebRequest.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注