简体   繁体   中英

Call a POST method (REST) from a webservice

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 method should not return IEnumerable but most likely IEnumerator since you are using coroutine.

And since it is a coroutine, you need to use the following to trigger it:

 StartCoroutine(Scores.getInstance().saveScore("POST", 50));

如果未显示POSTING,则不会调用您的函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM