Cute_demon_attacks/meng_yao/Assets/communal/web/web.cs

43 lines
1.4 KiB
C#
Raw Normal View History

2024-10-29 20:47:58 +08:00
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
public class web : MonoBehaviour
{
public static async Task<string> SendRequest(string url, string method = "GET", string jsonData = null)
{
using (UnityWebRequest request = new UnityWebRequest(url, method))
{
if (method == "POST" && jsonData != null)
{
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
}
else
{
request.downloadHandler = new DownloadHandlerBuffer();
}
// Send the request and await the response
var operation = request.SendWebRequest();
while (!operation.isDone)
await Task.Yield();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"Error: {request.error}");
return null;
}
else
{
return request.downloadHandler.text;
}
}
}
}