How to send json data to RESTful API in Unity3D?

Good afternoon friends!

I am a programmer and I’m a little time learning about the Unity and the game development universe. I came a doubt that I could not find the answer very well. What is the best architecture or solution to work with a mobile multiplayer game using a restful webservice? It’s possible? It is the best way to do something online multiplayer?

I’ve been studying a bit WWWForm class and tried to simulate sending data via JSON using JSONObject but without much success. I can not actually send a javascript object.

An example:

public void enviar(JSONObject json, Objeto obj)
{
    string url = "http://myurl/unity.php";

    WWWForm form = new WWWForm();

    form.AddField("var1", "[{\"Nome\":\""+obj.name+"\"}]");

    WWW www = new WWW(url, form);

    StartCoroutine(WaitForRequest(www));
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;

        // check for errors
    if(www.error == null)
    {
        Debug.Log("WWW Ok!: " + www.text);
    } else {
        Debug.Log("WWW Error: "+ www.error);
    }   
}

and my PHP file I have the following test:

$t = $_POST['var1'];
$novot = json_decode($t);

foreach($novot as $novo){
$fp = fopen("bloco1.txt","a");

$escreve = fwrite($fp, $novo);

fclose($fp);}

All I can back is a stdClass, I can handle, but that to me is something very manual. There is no simple and correct way of working with webservices?
Thanks in advance!

I would suggest using just straight WWW and passing your JSON as a byte array using the overload that takes the url, data and headers:

1 Like

Thanks for the answer! I looked but I was not sure yet. In any case, I think that the best solution can not be even connect via a web service but something like the Photon. I’m still studying it and even to a little lost.

Check the following RestClient for Unity, working with promises is better!
GitHub - proyecto26/RestClient: 🦄 A Promise based REST and HTTP client for Unity 🎮 (Supported all platforms)

Also you can see the demo, it’s very easy!

1 Like

Nice necroposting

3 Likes