using System; using System.Collections; using UnityEngine; using UnityEngine.Networking; public delegate void RequestDelegate(UnityWebRequest.Result status, string data); public static class WebRequest { private static readonly string server = "http://localhost:3000/api/"; public static void Get(MonoBehaviour behaviour, string url, RequestDelegate action) { behaviour.StartCoroutine(GetRequest(server+url, action)); } public static void Post(MonoBehaviour behaviour, string url, string jsonData, RequestDelegate action) { behaviour.StartCoroutine(PostRequest(server + url, jsonData, action)); } public static void PostFile(MonoBehaviour behaviour, string url, string filePath, RequestDelegate action) { behaviour.StartCoroutine(PostFileRequest(server + url, filePath, action)); } private static IEnumerator GetRequest(string url, RequestDelegate action) { using (UnityWebRequest request = UnityWebRequest.Get(url)) { request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); action(request.result, request.downloadHandler.text); } } private static IEnumerator PostRequest(string url, string jsonData, RequestDelegate action) { var request = new UnityWebRequest(url, "POST"); byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(jsonData); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); action(request.result, request.downloadHandler.text); } private static IEnumerator PostFileRequest(string url, string filePath, RequestDelegate action) { var request = new UnityWebRequest(url, "POST"); request.uploadHandler = new UploadHandlerFile(filePath); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "multipart/form-data"); yield return request.SendWebRequest(); action(request.result, request.downloadHandler.text); } }