1
This commit is contained in:
62
Unity/Scripts/Network/WebProvider.cs
Normal file
62
Unity/Scripts/Network/WebProvider.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using UnityEngine.Networking;
|
||||
using System;
|
||||
using System.Threading;
|
||||
namespace BITKit.HttpNet
|
||||
{
|
||||
[System.Serializable]
|
||||
public sealed class UnityWebRequest : WebProvider
|
||||
{
|
||||
public override async UniTask<string> GetAsync(string url, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await UniTask.SwitchToMainThread(cancellationToken);
|
||||
using (var request = UnityEngine.Networking.UnityWebRequest.Get(url))
|
||||
{
|
||||
await request.SendWebRequest();
|
||||
if (cancellationToken != default)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw new OperationCanceledException();
|
||||
}
|
||||
}
|
||||
if (request.result is UnityEngine.Networking.UnityWebRequest.Result.Success)
|
||||
{
|
||||
return request.downloadHandler.text;
|
||||
}
|
||||
else
|
||||
{
|
||||
var e = (request) switch
|
||||
{
|
||||
_ => "HttpError",
|
||||
};
|
||||
throw new System.Net.Http.HttpRequestException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
public override async UniTask<string> PostAsync<T>(string url, T value, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await UniTask.SwitchToMainThread(cancellationToken);
|
||||
switch (value)
|
||||
{
|
||||
case String _string:
|
||||
using (var request = UnityEngine.Networking.UnityWebRequest.Post(url, _string))
|
||||
{
|
||||
await request.SendWebRequest();
|
||||
return request.downloadHandler.text;
|
||||
}
|
||||
case WWWForm _wwwForm:
|
||||
using (var request = UnityEngine.Networking.UnityWebRequest.Post(url, _wwwForm))
|
||||
{
|
||||
await request.SendWebRequest();
|
||||
return request.downloadHandler.text;
|
||||
}
|
||||
default:
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user