- Home /
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?
Answer by Dave-Carlile · Jan 08, 2016 at 09:45 PM
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: https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
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
Thank you, it was that, I also had to change the return to IEnumerator.
Answer by jdnichollsc · Oct 20, 2017 at 09:12 AM
Check my plugin for Unity, working with promises is better! https://github.com/proyecto26/RestClient (Supported all platforms)
Let me know what you think, Nicholls
Your answer
Follow this Question
Related Questions
Post highscore to Facebook 0 Answers
How can I send http request from not-main thread? 1 Answer
Pass Headers and Arguments in UnityWebRequest POST Method Object 1 Answer
HTTP PUT in Unity for iOS? 2 Answers
post to wall facebook 0 Answers