Framework/Assets/TestScripts/Http/WebRequestTest.cs

83 lines
2.1 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MotionFramework;
using MotionFramework.Scripts.Runtime.Engine.Engine.Network.WebRequest;
using UnityEngine;
public class WebRequestTest : MonoBehaviour
{
CancellationTokenSource GetFileCan = new CancellationTokenSource();
private void Awake()
{
MotionEngine.Initialize(this, HandleMotionFrameworkLog);
MotionEngine.CreateModule<WebRequestManager>();
}
private async void Start()
{
TimeOut();
//get 获取
try
{
await WebRequestManager.Instance.GetFileAsync("http://localhost:5062/Home", procss => { Debug.Log($"下载进度: {procss}%"); }, GetFileCan.Token);
}
catch (OperationCanceledException)
{
Debug.LogError("异常!");
}
//表单提交
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("id", "123123");
dic.Add("name", "123123");
await WebRequestManager.Instance.PostFormAsync("http://localhost:5062/Home", dic, procss =>
{
Debug.Log($"提交进度: {procss}%");
}, GetFileCan.Token);
}
catch (OperationCanceledException)
{
Debug.LogError("异常!");
}
}
async void TimeOut()
{
//两秒钟后结束请求
await Task.Delay(TimeSpan.FromSeconds(1));
GetFileCan.Cancel();
}
private void HandleMotionFrameworkLog(ELogLevel logLevel, string log)
{
if (logLevel == ELogLevel.Log)
{
UnityEngine.Debug.Log(log);
}
else if (logLevel == ELogLevel.Error)
{
UnityEngine.Debug.LogError(log);
}
else if (logLevel == ELogLevel.Warning)
{
UnityEngine.Debug.LogWarning(log);
}
else if (logLevel == ELogLevel.Exception)
{
UnityEngine.Debug.LogError(log);
}
else
{
throw new NotImplementedException($"{logLevel}");
}
}
}