I am still a little unclear on how to handle POST request data especially bound for a RESTfull server for the purpose of quarrying a database. currently we have a noSQL database in place that expects curl-i notation. (I don’t know how this directly works was just given list of “acceptable” commands)
currently all I know how to do is actions that require just a url (getting X number of records at known location [Yrecords starting at positionX]). but what I need to implement is searching which requires a special formatted POST request, and the documentation is really no help at all. the expected statement in curl-i is:
curl -i "urlTarget" -XPOST -d'{keyValue:"targetValue"}'
so what/how do I give this to the server using the WWW class call? do I need to wrap this -d'{keyValue:"targetValue"}'
in a WWWForm, hand it using a byte[]
, or do more rigorous string magic on it?
if post request data must be given in the immediate header as with the question then it should be placed in a hashtable, and then encoded into a WWW call as a header like so:
var encoding = new System.Text.UTF8Encoding();
var postHeader = new Hashtable();
postHeader.Add("Content-Type", "text/json");
postHeader.Add("Content-Length", jsonString.Length);
print("jsonString: " + jsonString);
var request = WWW(postScoreURL, encoding.GetBytes(jsonString), postHeader);
yield request;
though keep in mind that even though the encoding reads as json the formatting might not be strict json, but a modification thereof.
in regards to doing this through WWWForm this requires either talking to a specific script on the server, or talking to the only script on the given server, and is detailed in my answer here
In my case to connect to .net web api (rest) I did this:
WWWForm form = new WWWForm();
form.AddField("facebookID", facebookID);
//
// I dont know why, but I have to put the parameters repeated in the url and in the WWWForms
// If I put the post argument only in the WWWForm or only in the url the request returns 404
//
string url = "http://site.net/api/facebookusers/?facebookID=" + facebookID;
Hashtable header = new Hashtable();
header.Add("Content-Type", "application/x-www-form-urlencoded");
WWW www = new WWW(url, form.data, header);
StartCoroutine( WaitForRequest( www ) );
I just finished writing a ASP.NET MVC4 API service to talk with Unity3d. My controller logic talks to a live database (via entity), but that shouldn’t matter.
Unity side my logic looks something like this.
var form = new WWWForm();
form.AddField("key", key);
form.AddField("content", content);
//Secure method
var www = new WWW(Domain+SaveUrl, form.data, AuthCookie.SessionCookie);
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
callback.Invoke(new ApiResult
{
HasError = true,
Message = www.error
});
}
else
{
callback.Invoke(new ApiResult());
}
The callback is a action delegate for communicating results back to consumers of this service client.