Unity - UnityWebRequest辅助类

Unity - UnityWebRequest辅助类

Unity中对Http请求提供了UnityWebRequest 和 WWW
最常用的是 UnityWebRequest.Get 和 UnityWebRequest.Post
为避免使用UnityWebRequest时重复编写代码,现对常用的方法进行封装,分为对 协程 的实现方法和对 UniTask 的实现方法,按自身需求选择其一即可

协程

using System;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine;

public static class UnityWebRequestHelper
{
    //保证传入参数不为空
    static void ParamsCheck(string url, object @object)
    {
        if (string.IsNullOrEmpty(url))
            throw new ArgumentNullException("url");

        if (@object is null)
            throw new ArgumentNullException("@object");
    }

    /// 
    /// 获取字符串
    /// 
    /// 请求成功时调用返回数据
    /// 请求失败时调用返回数据
    public static IEnumerator Get(string url, Action<string> onSuccess, Action onFail = null)
    {
        ParamsCheck(url, onSuccess);

        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            yield return request.SendWebRequest();
            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"对 {url} 请求失败。");
                onFail?.Invoke();
                yield break;
            }
            onSuccess(request.downloadHandler.text);
        }
    }

    /// 
    /// 获取数据流
    /// 
    /// 请求成功时调用返回数据
    /// 请求失败时调用返回数据
    public static IEnumerator Get(string url, Action<byte[]> onSuccess, Action onFail = null)
    {
        ParamsCheck(url, onSuccess);

        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            yield return request.SendWebRequest();
            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"对 {url} 请求失败。");
                onFail?.Invoke();
                yield break;
            }
            onSuccess(request.downloadHandler.data);
        }
    }

    /// 
    /// 获取字符串
    /// 
    /// 请求成功时调用返回数据
    /// 请求失败时调用返回数据
    public static IEnumerator Post(string url, WWWForm form, Action<string> onSuccess, Action onFail = null)
    {
        ParamsCheck(url, onSuccess);

        using (UnityWebRequest request = UnityWebRequest.Post(url, form))
        {
            yield return request.SendWebRequest();
            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"对 {url} 请求失败。");
                onFail?.Invoke();
                yield break;
            }
            onSuccess(request.downloadHandler.text);
        }
    }

    /// 
    /// 获取数据流
    /// 
    /// 请求成功时调用返回数据
    /// 请求失败时调用返回数据
    public static IEnumerator Post(string url, WWWForm form, Action<byte[]> onSuccess, Action onFail = null)
    {
        ParamsCheck(url, onSuccess);

        using (UnityWebRequest request = UnityWebRequest.Post(url, form))
        {
            yield return request.SendWebRequest();
            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"对 {url} 请求失败。");
                onFail?.Invoke();
                yield break;
            }
            onSuccess(request.downloadHandler.data);
        }
    }
}

调用示例:

using UnityEngine;

public class TestUWRHelper : MonoBehaviour
{
    void Awake()
    {
        StartCoroutine(UnityWebRequestHelper.Get("baidu.com", LogString));
    }

    void LogString(string str)
    {
        Debug.Log(str);
    }
}

UniTask

UniTask插件:https://github.com/Cysharp/UniTask

using System;
using UnityEngine.Networking;
using UnityEngine;
using Cysharp.Threading.Tasks;

public static class UnityWebRequestHelper
{
    /// 
    /// 获取字符串
    /// 
    /// 响应结果的字符串 当请求失败时为Null
    /// url为空
    public static async UniTask<string> GetString(string url) => await Get(url) as string;

    /// 
    /// 获取数据流
    /// 
    /// 响应结果的数据流 当请求失败时为Null
    /// url为空
    public static async UniTask<byte[]> GetBytes(string url) => await Get(url, ResultType.Bytes) as byte[];

    /// 
    /// 获取AssetBundle
    /// 
    /// 响应下载的AssetBundle 当请求失败时为Null
    /// url为空
    public static async UniTask<AssetBundle> GetAssetBundle(string url)
    {
        if (string.IsNullOrEmpty(url))
            throw new ArgumentNullException("url");

        using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url))
        {
            try
            {
                await request.SendWebRequest();
                return (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
            }
            catch (Exception e)
            {
                Debug.LogError($"对 {url} 请求失败。\n{e.Message}");
                return null;
            }
        }
    }

    /// 
    /// 获取字符串
    /// 
    /// 
    /// 响应结果的字符串 当请求失败时为Null
    /// url为空
    public static async UniTask<string> Post4String(string url, WWWForm form) => await Post(url, form, ResultType.String) as string;

    /// 
    /// 获取数据流
    /// 
    /// 响应结果的数据流 当请求失败时为Null
    /// url为空
    public static async UniTask<byte[]> Post4SBytes(string url, WWWForm form) => await Post(url, form, ResultType.Bytes) as byte[];
    
    enum ResultType
    {
        String,
        Bytes
    }

    //Get重复部分代码
    static async UniTask<object> Get(string url, ResultType type = ResultType.String)
    {
        if (string.IsNullOrEmpty(url))
            throw new ArgumentNullException("url");

        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            try
            {
                await request.SendWebRequest();
                var handler = request.downloadHandler;
                return type == ResultType.String ? handler.text : handler.data;
            }
            catch (Exception e)
            {
                Debug.LogError($"对 {url} 请求失败。\n{e.Message}");
                return null;
            }
        }
    }

    //Post重复部分代码
    static async UniTask<object> Post(string url, WWWForm form, ResultType type = ResultType.String)
    {
        if (string.IsNullOrEmpty(url))
            throw new ArgumentNullException("url");

        if (form is null)
            throw new ArgumentNullException("form");

        using (UnityWebRequest request = UnityWebRequest.Post(url, form))
        {
            try
            {
                await request.SendWebRequest();
                var handler = request.downloadHandler;
                return type == ResultType.String ? handler.text : handler.data;
            }
            catch (Exception e)
            {
                Debug.LogError($"对 {url} 请求失败。\n{e.Message}");
                return null;
            }
        }
    }
}

调用示例:

using UnityEngine;

public class TestUWRHelper : MonoBehaviour
{
    async void Awake()
    {
        LogString(await UnityWebRequestHelper.GetString("baidu.com"));
    }

    void LogString(string str)
    {
        Debug.Log(str);
    }
}

你可能感兴趣的:(Unity,C#,unity,c#,游戏引擎)