/// <summary>
    /// 发送HTTP请求
    /// </summary>
    /// <returns>HTTP引擎状态</returns>
    /// <param name="type">HTTP请求类型</param>
    /// <param name="url">服务器URL地址</param>
    /// <param name="success">请求成功回调函数</param>
    /// <param name="data">需要传递的数据</param>
    /// <param name="autoMask">是否自动开启操作屏蔽遮罩层</param>
    /// <param name="timeOut">请求超时秒数</param>
    public void SendRequest(HTTP_REQUEST_TYPE type, string url, SuccessCallBack success, string data = "", bool autoMask = true, float timeOut = 5.0f)
    {
        if (type == HTTP_REQUEST_TYPE.Post && data == "")
        {
#if UNITY_EDITOR
            Debug.LogError("使用POST方式请求服务器,data数据不能为空!");
#endif
            return;
        }

        if (_Processing)
        {
#if UNITY_EDITOR
            Debug.LogError("HTTP引擎正在请求服务器!");
#endif
            return;
        }

        Coroutiner.Start(
            _SendRequestCallback(type, url, success, data, autoMask, timeOut)
            );
    }
Esempio n. 2
0
        /// <summary>
        /// 请求HTTP数据
        /// </summary>
        /// <param name="type">请求类型(来自服务器)</param>
        /// <param name="url">URL地址</param>
        /// <param name="successResponse">成功请求的回调函数(服务器返回的字符串)</param>
        /// <param name="errorResponse">失败的回调函数(服务器返回的状态号,错误信息,失败的URL地址,失败的数据)</param>
        /// <param name="data">数据(Key=>参数的名字,Value=>参数的值)</param>
        /// <param name="timeOut">过期秒数</param>
        /// <returns></returns>
        public string Request(
            HTTP_REQUEST_TYPE type,
            string url,
            string str
            )
        {
            Debug.Log("type:" + type.ToString());
            Debug.Log("url:" + url);
            Debug.Log("str:" + str);
            Dictionary <string, string> data = new Dictionary <string, string>();

            string[] strList = str.Split(',');
            for (int i = 0; i < strList.Length; i++)
            {
                string[] strs = (strList[i]).Split(':');
                if (strs.Length == 2)
                {
                    data.Add(strs[0], strs[1]);
                }
            }

            int timeOut = 10;

            if (type == HTTP_REQUEST_TYPE.Post && (data == null || data.Count == 0))
            {
                Debug.LogError("使用HTTP的POST方式请求服务器,表单数据不能为空!");
                return(null);
            }

            if (_Networking)
            {
                Debug.LogError("HTTP引擎正在请求服务器!");
                return(null);
            }
            return(_Request(type, url, data, timeOut));
        }
Esempio n. 3
0
        private string _Request(
            HTTP_REQUEST_TYPE type,
            string url,
            Dictionary <string, string> data,
            int timeOut
            )
        {
            string debug = "URL地址:" + url + "\n";

            debug += "数据:" + HttpUtility.GetOriginalDataString(data) + "\n";
            debug += "请求类型:" + type.ToString().ToUpper() + "\n";
            DateTime debugTime = DateTime.UtcNow;

            //生成请求
            UnityWebRequest engine;

            if (type == HTTP_REQUEST_TYPE.Get)
            {
                string getData = HttpUtility.GetOriginalDataString(data);
                url = url + (getData != "" ? "?" : "") + getData;

                engine = UnityWebRequest.Get(url);
            }
            else
            {
                WWWForm postData = new WWWForm();
                foreach (string keyword in data.Keys)
                {
                    postData.AddField(keyword, data[keyword]);
                }

                engine = UnityWebRequest.Post(url, postData);
            }

            engine.timeout = timeOut;

            engine.SendWebRequest();

            debug += "消耗时间:" + (DateTime.UtcNow - debugTime).TotalMilliseconds / 1000 + "秒\n";

            //网络问题
            if (engine.isNetworkError)
            {
                Debug.LogError("网络错误:" + engine.error + "\n" + debug);

                engine.Dispose();
            }

            //服务器报错
            if (engine.isHttpError)
            {
                debug  = "服务器报错(" + engine.responseCode + "):" + engine.error + "\n" + debug;
                debug += "服务器返回值:" + engine.downloadHandler.text;
                Debug.LogError(debug);

                engine.Dispose();
            }

            //请求成功
            Debug.Log("请求成功:" + debug + "服务器返回值:" + engine.downloadHandler.text);

            System.Threading.Thread.Sleep(500);
            string response = engine.downloadHandler.text;

            engine.Dispose();

            JsonData jsonData = JsonMapper.ToObject(response);

            return(jsonData["Code"].ToString());
        }
    /// <summary>
    /// 通过协同发送异步HTTP请求
    /// </summary>
    /// <returns>HTTP请求协同</returns>
    /// <param name="request">HTTP请求数据</param>
    private IEnumerator _SendRequestCallback(HTTP_REQUEST_TYPE type, string url, SuccessCallBack success, string data, bool autoMask, float timeOut)
    {
        _Processing = true;

        //if(autoMask)
        //{
        //    UIDispatcher.WaitMask(true);
        //}

#if UNITY_EDITOR
        string debug = "URL地址:" + url + "\n";
        debug += "数据:" + data + "\n";
        DateTime debugTime = DateTime.UtcNow;
#endif

        //判断请求类型,生成请求头
        if (type == HTTP_REQUEST_TYPE.Get)
        {
            _WWW = new WWW(url + (data != "" ? ("?" + data) : ""));
        }
        else
        {
            _WWW = new WWW(
                url,
                System.Text.UTF8Encoding.UTF8.GetBytes(data),
                new Dictionary <string, string>()
            {
                { "Content-Type", "application/json; charset=utf-8" }
            }
                );
        }

        //设置HTTP请求过期时间
        //TimeClock.One.New(
        //    "HttpEngineTimeOut",
        //    timeOut,
        //    delegate
        //    {
        //        _WWW.Dispose();
        //    }
        //);

        yield return(_WWW);

#if UNITY_EDITOR
        debug += "消耗时间:" + (DateTime.UtcNow - debugTime).TotalMilliseconds / 1000 + "秒\n";
#endif

        _Processing = false;

        //if (autoMask)
        //{
        //    UIDispatcher.WaitMask(false);
        //}

        bool haveError = false;
        bool isTimeOut = false;

        try
        {
            haveError = _WWW.error != null;
            //TimeClock.One.Cancel("HttpEngineTimeOut", false);
        }
        catch
        {
            //UIMessageBox.Alert(
            //    "请求超时,是否重试?",
            //    delegate
            //    {
            //        HttpEngine.One().SendRequest(
            //            type,
            //            url,
            //            success,
            //            data,
            //            autoMask,
            //            timeOut
            //        );
            //    },
            //    false,
            //    "网络错误"
            //);
            isTimeOut = true;
        }

        if (!isTimeOut)
        {
#if UNITY_EDITOR
            if (haveError)
            {
                Debug.LogError(debug = "服务器错误" + _WWW.error + "!" + debug + "\n");
            }
            else
            {
                Debug.Log(debug = "请求成功!" + debug + "服务器返回值:" + _WWW.text + "\n");
            }
#endif

            if (haveError)
            {
                //UIMessageBox.Alert(
                //    "通讯错误,是否重试?",
                //    delegate
                //    {
                //        HttpEngine.One().SendRequest(
                //            type,
                //            url,
                //            success,
                //            data,
                //            autoMask,
                //            timeOut
                //        );
                //    },
                //    false,
                //    "网络错误"
                //);
                _WWW.Dispose();
            }
            else
            {
                string serverData = _WWW.text;
                _WWW.Dispose();
                success(serverData);
            }
        }
#if UNITY_EDITOR
        else
        {
            Debug.LogError(debug = "服务器响应超时!" + debug);
        }
#endif
    }