Bootstrap

Unity中Http框架

介绍

最近做了ASP.NET Web应用程序(.Net Framework)的Http服务,所以想也把之前我的Http框架也整理一下发布出来供大家参考。

框架代码

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

public class NetWorkHttpManager : MonoBehaviour
{
    #region 属性

    /// <summary>
    /// Web请求回调
    /// </summary>
    private Action<CallBackArgs> m_CallBack;

    /// <summary>
    /// Web请求回调数据
    /// </summary>
    private CallBackArgs m_CallBackArgs;

    /// <summary>
    /// 是否繁忙
    /// </summary>
    private bool m_IsBusy = false;

    /// <summary>
    /// 供外部访问是否繁忙
    /// </summary>
    public bool IsBusy
    {
        get
        {
            return m_IsBusy;
        }
    }

    /// <summary>
    /// 网络字典
    /// </summary>
    private Dictionary<string, string> m_httpDic = new Dictionary<string, string>();

    #endregion

    public static NetWorkHttpManager Instance;

    private void Awake()
    {
        Instance = this;
        m_CallBackArgs = new CallBackArgs();
    }


    #region 键值对

    /// <summary>
    /// 添加键值对
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    public void AddValueToDic(string key, string value)
    {
        m_httpDic.Add(key,value);
    }

    /// <summary>
    /// 移除字典
    /// </summary>
    /// <param name="key"></param>
    public void RemoveValueToDic(string key)
    {
        if (m_httpDic.ContainsKey(key))
        {
            m_httpDic.Remove(key);
        }
    }

    /// <summary>
    /// 获取字典
    /// </summary>
    public Dictionary<string,string> GetDic()
    {
        return m_httpDic;
    }

    /// <summary>
    /// 清楚字典
    /// </summary>
    public void ClearDic()
    {
        m_httpDic.Clear();
    }

    #endregion

    #region SendData 发送Web数据

    public void SendData(string url, Action<CallBackArgs> callBack, bool IsPost = false, Dictionary<string, string> dic = null)
    {
        if (m_IsBusy) return;
        m_IsBusy = true;
        m_CallBack = callBack;
        if (!IsPost) GetUrl(url);
        else
        {
            PostUrl(url,dic);
        }
    }

    #endregion

    #region GetUrl Get请求

    /// <summary>
    /// Get请求
    /// </summary>
    /// <param name="url"></param>
    private void GetUrl(string url)
    {
        UnityWebRequest req = UnityWebRequest.Get(url);
        StartCoroutine(Request(req));
    }

    #endregion

    #region PostUrl Post请求

    /// <summary>
    /// Post请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="json"></param>
    private void PostUrl(string url, Dictionary<string, string> dic)
    {
        UnityWebRequest req = UnityWebRequest.Post(url, dic);

        StartCoroutine(Request(req));
    }

    #endregion

    #region Request 请求服务器

    /// <summary>
    /// 请求服务器
    /// </summary>
    /// <param name="req"></param>
    /// <returns></returns>
    private IEnumerator Request(UnityWebRequest req)
    {
        yield return req.SendWebRequest();
        m_IsBusy = false;

        //没有错误
        if (string.IsNullOrEmpty(req.error))
        {
            if (req.downloadHandler.text == "null")
            {
                if (m_CallBack != null)
                {
                    m_CallBackArgs.HasError = true;
                    m_CallBackArgs.ErrorMsg = "未请求到用户";
                    m_CallBack(m_CallBackArgs);
                }
            }
            else
            {
                if (m_CallBack != null)
                {
                    m_CallBackArgs.HasError = false;
                    m_CallBackArgs.ErrorMsg = "";
                    m_CallBackArgs.Value = req.downloadHandler.text;
                    m_CallBack(m_CallBackArgs);
                }
            }
        }
        //有错误
        else
        {
            if (m_CallBack != null)
            {
                m_CallBackArgs.HasError = true;
                m_CallBackArgs.ErrorMsg = req.error;
                m_CallBack(m_CallBackArgs);
            }
        }
    }

    #endregion

}

#region 回调类

/// <summary>
/// Web请求回调数据
/// </summary>
public class CallBackArgs : EventArgs
{
    /// <summary>
    /// 是否有错误
    /// </summary>
    public bool HasError;

    /// <summary>
    /// 错误原因
    /// </summary>
    public string ErrorMsg;

    /// <summary>
    /// 返回值
    /// </summary>
    public string Value;
}

#endregion

使用方法

		//Get请求
        if (!NetWorkHttpManager.Instance.IsBusy) 
        {
            NetWorkHttpManager.Instance.SendData("urlxxxxxxxxxxxxx", (cb) => 
            {
                if (cb.HasError) 
                {
                    Debug.LogError(cb.ErrorMsg);
                }
                else 
                {
                    Debug.LogError(cb.Value);
                }
            });
        }
		
		//Post请求
		if (!NetWorkHttpManager.Instance.IsBusy) 
        {
            JsonData jsonData = new JsonData();
            jsonData["UserName"] = "ck";
            jsonData["Pwd"] = "ck123";

            NetWorkHttpManager.Instance.ClearDic();
            NetWorkHttpManager.Instance.AddValueToDic("", jsonData.ToJson());

            NetWorkHttpManager.Instance.SendData("http://192.168.1.120:8023/api/TestWeb", (cb) =>
            {
                if (cb.HasError)
                {
                    Debug.LogError(cb.ErrorMsg);
                }
                else
                {
                    Debug.LogError(cb.Value);
                }
            }, true, NetWorkHttpManager.Instance.GetDic());

        }

总结

感谢大家的支持!

;