You often require 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 specifically designed to handle HTTP communications. It provides set of functions especially Get and Post function to deal with data retrieval and data post operations: Here are the ways to use it:
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.
No comments:
Post a Comment