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


GetMethod.cs
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...";
        string url = "https://my-json-server.typicode.com/typicode/demo/posts";
        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
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...";
        string url = "https://my-json-server.typicode.com/typicode/demo/posts";
        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;
        }
    }
}