首页 学习日记正文

Http Get & Post

阿沐 学习日记 2019-08-22 549 0 unity

Http Get & Post


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
/*
四川麻将
时间:2017.6.12
作者:阿沐
版本:2.6
*/
namespace util
{
public class Http{
        /// <summary>
        /// 通过 Get方式 向服务器发送请求
        /// </summary>
        /// <param name="url">远程服务器 请求路径</param>
        /// <param name="parent">MonoBehavior 对象</param>
        /// <param name="action">回调函数</param>
        public static void doGet(string url, MonoBehaviour parent, MyAction<object> action = null)
        {
            parent.StartCoroutine(Connect(url, action));
        }
        /// <summary>
        /// 通过 Post方式 向服务器发送请求
        /// </summary>
        /// <param name="url">远程服务器的 请求地址</param>
        /// <param name="parent">MonoBehaviour对象</param>
        /// <param name="action">回调函数</param>
        /// <param name="form">WWWForm</param>
        public static void doPost(string url, MonoBehaviour parent, MyAction<object> action = null,WWWForm form=null)
        {
            parent.StartCoroutine(Connect(url,action,form));
        }

        /// <summary>
        /// 通过 WWW 方式 连接
        /// </summary>
        static IEnumerator getLoad(string url,MyAction<object> action, WWWForm form = null)
        {
            WWW www = form == null ? new WWW(url) : new WWW(url, form);
            yield return www;
            if (string.IsNullOrEmpty(www.error))
            {
                if (action != null)
                {
                    action(www.text);
                }
            }
        }

        /// <summary>
        /// 通过 UnityWebRequest 方式 连接
        /// </summary>
        static IEnumerator Connect(string url, MyAction<object> action, WWWForm form = null)
        {
            UnityWebRequest request = null;
            if (form == null)
            {
                request = UnityWebRequest.Get(url);
            }
            else
            {
                request = UnityWebRequest.Post(url,form);
            }
            request.timeout = 30;
            yield return request.SendWebRequest();
            if (request.isNetworkError)
            {
                Debug.Log("连接超时");
            }
            else if (!request.isHttpError)
            {
                if (action != null)
                {
                    Debug.Log("request.text="+ request.downloadHandler.text);
                    action(request.downloadHandler.text);
                    action = null;
                }
            }
            else
            {
                Debug.Log("连接有误");
            }
            request = null;
        }
        
    }
}


打赏

评论

Music