美文网首页
Unity 数据传输静态类

Unity 数据传输静态类

作者: ShawnWeasley | 来源:发表于2020-08-13 16:46 被阅读0次

在写这篇的时候提到过一个数据传输工具,但是当时是别人的东西,只写了两个例子,这里稍微整理一下,变成一个静态类工具,可以直接和服务器Get、Post、Delete等请求。

还是先讲使用方法:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    void Start()
    {
        //服务的地址接口
        string url = "http://192.168.222.222:8080/api/base/common/login";
        //直接Get请求,onError和onSuccess为回调
        WebRequests.Get(url, onError, onSuccess);
        //如果需要添加header
        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers.Add("Authentication", "Authentication");
        WebRequests.Get(url, onError, onSuccess, headers);
        //Post请求案例
        WWWForm form = new WWWForm();
        form.AddField("phone", "11111111111");
        form.AddField("password", "111111");
        WebRequests.Post(url, form, onError, onSuccess);
    }

    void onSuccess(string log)
    {
        Debug.Log("onSuccess:" + log);
    }

    void onError(string log)
    {
        Debug.Log("onError:" + log);
    }
}

然后是静态类工具代码:

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

/// <summary>
/// 网络请求类,四种请求方式区别可参考:https://blog.csdn.net/u010305706/article/details/51259649?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-4.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-4.channel_param
/// 常用的可能就是Get和Post,有时候也会用到Delete
/// </summary>
public static class WebRequests
{
    //WebRequests本身不继承MonoBehaviour,但调用IEnumerator协程需要MonoBehaviour
    //因此使用WebRequestsMonoBehaviour来调用StartCoroutine
    private class WebRequestsMonoBehaviour : MonoBehaviour { }

    private static WebRequestsMonoBehaviour webRequestsMonoBehaviour;

    //用于调用前防止未生成实例,可以通过统一的单例再优化一下
    private static void Init()
    {
        if (webRequestsMonoBehaviour == null)
        {
            GameObject gameObject = new GameObject("WebRequests");
            webRequestsMonoBehaviour = gameObject.AddComponent<WebRequestsMonoBehaviour>();
        }
    }

    //外部直接调用此处的Get函数,通过委托处理onError和onSuccess事件
    public static void Get(string url, Action<string> onError, Action<string> onSuccess, Dictionary<string, string> headers = null)
    {
        Init();
        webRequestsMonoBehaviour.StartCoroutine(IEGet(url, headers, onError, onSuccess));
    }

    private static IEnumerator IEGet(string url, Dictionary<string, string> headers, Action<string> onError, Action<string> onSuccess)
    {
        //因为UnityWebRequest继承IDisposable接口,参考https://www.cnblogs.com/wyt007/p/9304564.html
        //因此需要使用using关键字来控制资源的释放
        //我们在写一些临时变量并且希望用完即释放它的时候也可以去继承IDisposable接口
        using (UnityWebRequest unityWebRequest = UnityWebRequest.Get(url))
        {
            if (headers != null)
            {
                Debug.Log(headers.Count);
                foreach (var header in headers)
                {
                    unityWebRequest.SetRequestHeader(header.Key, header.Value);
                }
            }
            unityWebRequest.method = UnityWebRequest.kHttpVerbGET;

            yield return unityWebRequest.SendWebRequest();
            if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
            {
                onError(unityWebRequest.error);
            }
            else
            {
                onSuccess(unityWebRequest.downloadHandler.text);
            }
        }
    }

    public static void Delete(string url, Action<string> onError, Action<string> onSuccess, Dictionary<string, string> headers = null)
    {
        Init();
        webRequestsMonoBehaviour.StartCoroutine(IEDelete(url, headers, onError, onSuccess));
    }

    private static IEnumerator IEDelete(string url, Dictionary<string, string> headers, Action<string> onError, Action<string> onSuccess)
    {
        using (UnityWebRequest unityWebRequest = UnityWebRequest.Delete(url))
        {
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    unityWebRequest.SetRequestHeader(header.Key, header.Value);
                }
            }
            unityWebRequest.method = UnityWebRequest.kHttpVerbDELETE;

            yield return unityWebRequest.SendWebRequest();

            if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
            {
                onError(unityWebRequest.error);
            }
            else
            {
                onSuccess(unityWebRequest.downloadHandler.text);
            }
        }
    }

    public static void Post(string url, WWWForm postData, Action<string> onError, Action<string> onSuccess, Dictionary<string, string> headers = null)
    {
        Init();
        webRequestsMonoBehaviour.StartCoroutine(IEPost(url, postData, headers, onError, onSuccess));
    }

    private static IEnumerator IEPost(string url, WWWForm postData, Dictionary<string, string> headers, Action<string> onError, Action<string> onSuccess)
    {
        using (UnityWebRequest unityWebRequest = UnityWebRequest.Post(url, postData))
        {
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    unityWebRequest.SetRequestHeader(header.Key, header.Value);
                }

                foreach (var header in headers)
                {
                    Debug.Log(unityWebRequest.GetRequestHeader(header.Key));
                }
            }
            unityWebRequest.method = UnityWebRequest.kHttpVerbPOST;

            yield return unityWebRequest.SendWebRequest();

            if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
            {
                onError(unityWebRequest.error);
            }
            else
            {
                onSuccess(unityWebRequest.downloadHandler.text);
            }
        }
    }

    public static void Put(string url, string putData, Action<string> onError, Action<string> onSuccess, Dictionary<string, string> headers = null)
    {
        Init();
        webRequestsMonoBehaviour.StartCoroutine(IEPut(url, putData, headers, onError, onSuccess));
    }

    private static IEnumerator IEPut(string url, string putData, Dictionary<string, string> headers, Action<string> onError, Action<string> onSuccess)
    {
        using (UnityWebRequest unityWebRequest = UnityWebRequest.Put(url, putData))
        {
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    unityWebRequest.SetRequestHeader(header.Key, header.Value);
                }
            }
            unityWebRequest.method = UnityWebRequest.kHttpVerbDELETE;

            yield return unityWebRequest.SendWebRequest();

            if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
            {
                onError(unityWebRequest.error);
            }
            else
            {
                onSuccess(unityWebRequest.downloadHandler.text);
            }
        }
    }
}


这里仅写了普通的交互方法,未写一些资源的请求方法,如果有需要的小伙伴,可以自行参考这篇里的内容扩展该工具。

相关文章

网友评论

      本文标题:Unity 数据传输静态类

      本文链接:https://www.haomeiwen.com/subject/qxcidktx.html