I am trying to use WWW and WWWForm to call my POST method of a webservice to save scores.

My service is working, I tested it using the Advanced REST Client of Chrome:

The problem is in the client side… I have the following function to call my service:

public IEnumerable saveScore(String name, float score)
{
        Debug.Log("POSTING");
        WWWForm form = new WWWForm();
        form.AddField("dummy", "something");

        Dictionary<String, String> headers = form.headers;
        byte[] rawData = form.data;
        headers["arqamUserName"] = name;
        headers["arqamUserScore"] = score.ToString();

        // Post a request to an URL with our custom headers
        Debug.Log("CREATING WWW");
        WWW www = new WWW(url, rawData, headers);
        yield return www;
        Debug.Log("HAVE RESULTS");
        //.. process results from WWW request here...
        if (www.error!= null)
        {
             Debug.Log("Erro: " + www.error);
        }
        else
        {
            Debug.Log("All OK");
            Debug.Log("Text: " + www.text);
        }
}

And then, I just call the above function:

private bool test = false;

void Update()
{
    if (!test)
    {
        Debug.Log("Starting POST");
        Scores.getInstance().saveScore("POST", 50);
        Debug.Log("Finished POST");
        test = true;
    }
}

I have done other c# clients using restsharp… But I am having problems when doing it in Unity.

When I run my game and the function saveScore() is called, I get this Output:

Starting POST
Finished POST

What am I doing wrong?

Your saveScore method is a Coroutine. Since you return IEnumerator and use yield inside of the method, the compiler actually creates a special internal class to handle it as a state machine. When you call the method directly, all it does is return an instance of that class - it doesn’t actually execute the code at that time.

You need to run the Coroutine using StartCoroutine.

Some information about the internals here: yield statement - provide the next element in an iterator | Microsoft Learn

Also, in Unity the Coroutine method must be declared on a MonoBehaviour. Can’t tell if yours is based on the posted code.

edit: replaced IEnumerable with IEnumerator

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

Let me know what you think, Nicholls