유니티 C# Rest Api 사용법 간단 구현 통신 UnityWebRequest

반응형

코드 작성

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class RestApiExample : MonoBehaviour
{
    // URL to your API endpoint
    private string apiUrl = "https://jsonplaceholder.typicode.com/posts";

    // Start is called before the first frame update
    void Start()
    {
        // Example of a GET request
        StartCoroutine(GetRequest(apiUrl));

        // Example of a POST request
        StartCoroutine(PostRequest(apiUrl, "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"));
    }

    IEnumerator GetRequest(string url)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            string[] pages = url.Split('/');
            int page = pages.Length - 1;

            if (webRequest.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(pages[page] + ": Error: " + webRequest.error);
            }
            else
            {
                // Show results as text
                Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
            }
        }
    }

    IEnumerator PostRequest(string url, string jsonData)
    {
        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();

        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.Log("Error: " + request.error);
        }
        else
        {
            Debug.Log("Received: " + request.downloadHandler.text);
        }
    }
}
반응형