How to do Get Request in Unity C# | Get data from a URL in unity

 You are often required to access a URL/API endpoint in order to get/post data or communicate to a web server. For this reason, unity provides UnityWebRequest Class. The class is specifically designed to handle HTTP communications. It provides a set of functions especially the Get and Post function to deal with data retrieval and data post operations. In this tutorial, you will learn how to get data from a URL using this Unity Web Request:

Get Request: A common way to access data from a URL. Suppose you are trying to get JSON data from a URL/API (given below) and here is our working example URL

https://jsonplaceholder.typicode.com/todos/1

void Start()

    {

        string getURL = "https://jsonplaceholder.typicode.com/todos/1";

        StartCoroutine(GetReq(getURL));

    }

 

    IEnumerator GetReq(string url)

    {

        UnityWebRequest req = UnityWebRequest.Get(url);

        yield return req.SendWebRequest();//wait until request competed

 

        if (req.isNetworkError)//if the networkerror is true then, there is an error.

        {

            Debug.Log("Error While Sending: " + req.error);

        }

        else

        {

            Debug.Log("Received: " + req.downloadHandler.text);

        }

    }


If you have json string then you can deserailze it. Here is the detailed tutorail.

Post a Comment

0 Comments