using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using UnityEngine; namespace Touka { public class RequestHandler : MonoBehaviour { private static RequestHandler _instance; public static RequestHandler Instance { get { if (_instance != null) return _instance; _instance = FindObjectOfType(); if (_instance != null) return _instance; var obj = new GameObject(); _instance = obj.AddComponent(); return _instance; } } private void Awake() { if (_instance == null) { _instance = this; } else if (_instance != this) { Destroy(gameObject); } DontDestroyOnLoad(gameObject); } public void SendGetRequest(string url, Dictionary headers = null, Action callback = null ) { StartCoroutine(GetRequestCoroutine(url, headers, callback)); } public void SendPostRequest(string url, string jsonRequestBody, Dictionary headers = null, Action callback = null) { StartCoroutine(PostRequestCoroutine(url, jsonRequestBody, headers, callback)); } private static IEnumerator GetRequestCoroutine(string url, Dictionary headers, Action callback) { try { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } using (var response = (HttpWebResponse)request.GetResponse()) { var responseStream = response.GetResponseStream(); if (responseStream == null) { throw new Exception("responseStream is null"); } using (var reader = new StreamReader(responseStream)) { var jsonResponse = reader.ReadToEnd(); Debug.Log(jsonResponse); callback?.Invoke(0, jsonResponse); } } } catch (Exception e) { callback?.Invoke(-1, e.Message); } yield return null; } private static IEnumerator PostRequestCoroutine(string url, string jsonRequestBody, Dictionary headers, Action callback) { try { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } var byteArray = Encoding.UTF8.GetBytes(jsonRequestBody); request.ContentLength = byteArray.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(byteArray, 0, byteArray.Length); } using (var response = (HttpWebResponse)request.GetResponse()) { var responseStream = response.GetResponseStream(); if (responseStream == null) { throw new Exception("responseStream is null"); } using (var reader = new StreamReader(responseStream)) { var jsonResponse = reader.ReadToEnd(); callback?.Invoke(0, jsonResponse); } } } catch (Exception e) { callback?.Invoke(-1, e.Message); } yield return null; } } }