There are three primary methods for sending data to a server, formatted as an HTML Form using unity web request.
1st : Using WWWForm (which is a legacy method, that UnityWebRequest still supports)
IEnumerator ProcessRequest(string username, string password, string url, string age = null, string email = null)
{
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("password", password);
form.AddField("age", age);
form.AddField("email", email);
UnityWebRequest www = UnityWebRequest.Post(url, form);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
2nd: Using IMultipartFormSection
List<IMultipartFormSection> form = new List<IMultipartFormSection>();
form.Add(new MultipartFormDataSection("username", username));
form.Add(new MultipartFormDataSection("password", password));
form.Add(new MultipartFormDataSection("age", age != null ? age : "0"));
form.Add(new MultipartFormDataSection("email", email));
UnityWebRequest www = UnityWebRequest.Post(url, form);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
3rd: JSON Serialization
Use the JsonUtility class to convert Unity objects to and from the JSON format. - this would require some additional code
You would begin by creating a new class that would be used to serialize your form:
[Serializable]
public class myForm
{
public string username;
public string password;
public string age;
public string email;
}
The class is using the [Serializable] attribute, in order to work with the JSON serializer.
Then create an instance of your class, for example:
myForm form = new myForm();
form.username = "UsrNamesss";
form.password = "11111111";
form.age = "23";
form.email = "[email protected]";
And to wrap it up - Serialize it using JsonUtility and Post it using UnityWebRequest
IEnumerator ProcessRequest(string url, myForm form)
Convert it (which can be done on the other direction like this:
newForm = JsonUtility.FromJson<myForm>(json);
)
string json = JsonUtility.ToJson(myForm);
and just post it using UnityWebRequest:
UnityWebRequest www = UnityWebRequest.Post(url, form);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
I find the 3rd solution better in most cases as it allows me to better manage data and models within my apps.