Unity
[Unity] API 호출 방법
usingsystem
2022. 11. 8. 16:49
728x90
public class WebManager : MonoBehaviour
{
enum Method
{
POST,
GET,
UPDATE,
DELETE
}
string _baseUrl = "https://localhost:44351/api";
void Start()
{
TestResult res = new TestResult()
{
UserName = "tkddls",
Score = 1,
};
SendPostRequest("ranking", res, (uwr) =>
{
Debug.Log("post 호출");
});
SendGetAllRequest("ranking", (uwr) =>
{
Debug.Log("get 호출");
});
}
public void SendPostRequest(string url, object obj, Action<UnityWebRequest> callback)
{
StartCoroutine(CosendWebRequest(url, Enum.GetName(typeof(Method),Method.POST), obj, callback));
}
public void SendGetAllRequest(string url, Action<UnityWebRequest> callback)
{
StartCoroutine(CosendWebRequest(url, Enum.GetName(typeof(Method), Method.GET), null, callback));
}
IEnumerator CosendWebRequest(string url, string method, object obj, Action<UnityWebRequest> callback)
{
string sendUrl = $"{_baseUrl}/{url}/";
byte[] jsonByte = null;
if (obj != null)
{
string jsonStr = JsonUtility.ToJson(obj);
jsonByte = Encoding.UTF8.GetBytes(jsonStr);
}
var uwr = new UnityWebRequest(sendUrl, method);
uwr.uploadHandler = new UploadHandlerRaw(jsonByte);
uwr.downloadHandler = new DownloadHandlerBuffer();
uwr.SetRequestHeader("Content-Type", "application/json");
yield return uwr.SendWebRequest();
if (uwr.result != UnityWebRequest.Result.Success)
{
Debug.Log(uwr.result);
}
else
{
Debug.Log(uwr.downloadHandler.text);
callback.Invoke(uwr);
}
}
}
728x90