I'm not so experienced with C#, anyway I'm using the following function to post data to my own API:
public static JSONNode SaveObject(List<String> parameters){
var request = (HttpWebRequest)WebRequest.Create("http://example.com/query.php?");
var data = Encoding.ASCII.GetBytes(String.Join("",parameters));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream()){ stream.Write(data, 0, data.Length); }
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
// Debug.Log("RESPONSE: " + responseString);
// JSONNode object
var obj = JSON.Parse(responseString);
return obj;
}
Here's how I call it:
List<String> parameters = new List<String>();
parameters.Add("tableName=Posts"));
parameters.Add("&text=Text & more"));
parameters.Add("&number=123"));
// Save
var result = SaveObject(parameters);
Debug.Log("OBJECT SAVED: " + result.ToString());
I was fine with my SaveObject()
function until I've found out that the Text & more
String gets truncated to Text
in my JSON file to the "text" key (my API simply edits JSON files).
I know why that happens, it's because the String.Join("",parameters) generates a URL string that looks like "tableName=Posts&text=Text & more&number=123"
, so the & character between Text
and more
gets invalidated because my PHP code thinks it's a separator like the other &'s
So I can't figure out how to transform my SaveObject()
function to use a Dictionary of parameters instead of a String. If I'll use something like a <string, string>
dictionary, I think I'll solve my & character issue, nice Iìm using a Dictionary for the iOS code that calls my API