Unity UnityWebRequest

/****************************************************************************
 * 2021.3 DESKTOP-J98GMVJ
 ****************************************************************************/

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

namespace QFramework.Example
{
    public partial class LoginCamRaw : UIComponent
    {

        private void Awake()
        {
        }

        public string m_sServerAddress => "http://127.0.0.1/";
        public string m_sPostMsg => "https://www.shengyinyouju.cn/cBBQE6uuDk4g=";
        void Start()
        {
            //StartCoroutine(Get());
            //StartCoroutine(Post(m_sPostMsg));
        }

        IEnumerator Get()
        {
            UnityWebRequest webRequest = UnityWebRequest.Get(m_sServerAddress);

            yield return webRequest.SendWebRequest();
            //异常处理,很多博文用了error!=null这是错误的,请看下文其他属性部分
            if (webRequest.isHttpError || webRequest.isNetworkError)
                Debug.Log(webRequest.error);
            else
            {
                Debug.Log(webRequest.downloadHandler.text);
            }

        }

        // 外部调用 post 到服务器方法
        public void PostToServer(string m_sPostMsg)
        {
            StartCoroutine(Post(m_sPostMsg));
        }

        IEnumerator Post(string m_sPostMsg)
        {
            WWWForm form = new WWWForm();
            //键值对
            form.AddField("url", m_sPostMsg);

            UnityWebRequest webRequest = UnityWebRequest.Post(m_sServerAddress, form);

            yield return webRequest.SendWebRequest();
            //异常处理,很多博文用了error!=null这是错误的,请看下文其他属性部分
            if (webRequest.isHttpError || webRequest.isNetworkError)
                Debug.Log(webRequest.error);
            else
            {
                Debug.Log(webRequest.downloadHandler.text);
            }
        }

        protected override void OnBeforeDestroy()
        {
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39097425/article/details/114262450