59 lines
2.1 KiB
C#
59 lines
2.1 KiB
C#
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
|
|
{
|
|
throw new System.Net.Http.HttpRequestException(request.error);
|
|
}
|
|
}
|
|
}
|
|
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.PostWwwForm(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();
|
|
}
|
|
}
|
|
}
|
|
}
|