Get/Post REST API Data using HttpClient | Unity Game Engine


GetMethod.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using UnityEngine;
using UnityEngine.UI;
using System.Net.Http;
 
public class GetMethod : MonoBehaviour
{
    InputField outputArea;
 
    void Start()
    {
        outputArea = GameObject.Find("OutputArea").GetComponent<InputField>();
        GameObject.Find("GetButton").GetComponent<Button>().onClick.AddListener(GetData);
    }
 
    async void GetData()
    {
        outputArea.text = "Loading...";
        using(var httpClient = new HttpClient())
        {
            var response = await httpClient.GetAsync(url);
            if (response.IsSuccessStatusCode)
                outputArea.text = await response.Content.ReadAsStringAsync();
            else
                outputArea.text = response.ReasonPhrase;
        }
    }
}

PostMethod.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net.Http;
 
public class PostMethod : MonoBehaviour
{
    InputField outputArea;
 
    void Start()
    {
        outputArea = GameObject.Find("OutputArea").GetComponent<InputField>();
        GameObject.Find("PostButton").GetComponent<Button>().onClick.AddListener(PostData);
    }
 
    async void PostData()
    {
        outputArea.text = "Loading...";
        var postData = new Dictionary<string, string>();
        postData["title"] = "test data";
        using(var httpClient = new HttpClient())
        {
            var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(postData));
            if (response.IsSuccessStatusCode)
                outputArea.text = await response.Content.ReadAsStringAsync();
            else
                outputArea.text = response.ReasonPhrase;
        }
    }
}