美文网首页
UnityWebRequest

UnityWebRequest

作者: 玄策丶 | 来源:发表于2020-09-24 14:52 被阅读0次

    Get方法:

    using System.Collections;
    using System.Collections.Generic;
    using System.Net;
    using UnityEngine;
    using UnityEngine.Networking;
    public class UnityWebRequestTest: MonoBehaviour
    {
        string url = "https://www.baidu.com/";
        void Start()
        {
            StartCoroutine(GetRequest());
        }
        public IEnumerator GetRequest()
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
    
                yield return webRequest.SendWebRequest();
    
                if (webRequest.isHttpError || webRequest.isNetworkError)
                {
                    Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                }
                else
                {
                    Debug.Log(webRequest.downloadHandler.text);
                    JsonData jsonData = JsonMapper.ToObject(webRequest.downloadHandler.text);
                   text = jsonDate[0]["a"].ToString();
    
                }
            }
        }
    }
    

    Post方法:
    1、

    IEnumerator HttpLogin()
        {
            url = AppConst.WebUrl;
    
            WWWForm form = new WWWForm();
            form.AddField("username", username);
            form.AddField("password", password);
    
            using (UnityWebRequest webRequest = UnityWebRequest.Post(url,form))
            {
                yield return webRequest.SendWebRequest();
                if (webRequest.isHttpError || webRequest.isNetworkError)
                {
                    Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                }
                //代表通讯正常完成  不是代表消息接收成功;
                else
                {
                    Debug.Log(webRequest.downloadHandler.text);
                }
            }
        }
    

    2、

    public IEnumerator PostUrl(string url, string postData)
        {
            using (UnityWebRequest www = new UnityWebRequest(url,"POST"))
            {
                byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
                www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
                www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
                www.SetRequestHeader("Content-Type", "application/json");
                yield return www.Send();
                if (www.isError)
                {
                    Debug.Log(www.error);
                }
                else
                {
                    Debug.Log(www.downloadHandler.text);
                }
            }
        }
    

    完整工具代码封装(转)

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System;
    using UnityEngine.Networking;
    using System.Text;
    
    /// <summary>
    /// Http Request SDK 
    /// </summary>
    public class HttpTool : MonoBehaviour
    {
    
        private static HttpTool _instacne = null;
        public string baseUrl = "https://127.0.0.1:3000/";
        public string sKey = "zoo_visit_key";
    
        Dictionary<string, string> requestHeader = new Dictionary<string, string>();  //  header
        public static HttpTool Instance
        {
            get
            {
                if (_instacne == null)
                {
                    Debug.LogError("Awake error");
                }
                return _instacne;
            }
        }
    
        void Awake()
        {
            DontDestroyOnLoad(gameObject);
            HttpTool._instacne = gameObject.GetComponent<HttpTool>();
    
             //http header 的内容
            requestHeader.Add("Content-Type", "application/json");
            requestHeader.Add("sKey", sKey);
    
        }
    
        public void Get(string methodName, Action<string> callback)
        {
            StartCoroutine(GetRequest(methodName, callback));
        }
        public IEnumerator GetRequest(string methodName, Action<string> callback)
        {
            string url = baseUrl + methodName;
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
                //设置header
                foreach (var v in requestHeader)
                {
                    webRequest.SetRequestHeader(v.Key, v.Value);
                }
                yield return webRequest.SendWebRequest();
    
                if (webRequest.isHttpError || webRequest.isNetworkError)
                {
                    Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                    if (callback != null)
                    {
                        callback(null);
                    }
                }
                else
                {
                    if (callback != null)
                    {
                        callback(webRequest.downloadHandler.text);
                    }
                }
            }
        }
    
       //jsonString 为json字符串,post提交的数据包为json
        public void Post(string methodName,string jsonString, Action<string> callback)
        {
            StartCoroutine(PostRequest(methodName,jsonString,callback));
        }
        public IEnumerator PostRequest(string methodName, string jsonString, Action<string> callback)
        {
            string url = baseUrl + methodName;
           // Debug.Log(string.Format("url:{0} postData:{1}",url,jsonString));
            using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
            {
                byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
                webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
                webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
    
                foreach (var v in requestHeader)
                {
                    webRequest.SetRequestHeader(v.Key, v.Value);
                }
                yield return webRequest.SendWebRequest();
    
                if (webRequest.isHttpError || webRequest.isNetworkError)
                {
                    Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                    if (callback != null)
                    {
                        callback(null);
                    }
                }
                else
                {
                    if (callback != null)
                    {
                        callback(webRequest.downloadHandler.text);
                    }
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:UnityWebRequest

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