Post Json data with WWWform instead of http.request

Hello,

I had a perfectly working game with retrieving and posting scores to a database with this code.

public void SendScore(string name, int score)
	{
		Hashtable data = new Hashtable();
		data.Add("name", name);
		data.Add("score", score);

		HTTP.Request postRequest = new HTTP.Request("post", "https://Mygame.firebaseio.com/scores.json", data);
		postRequest.Send(( request ) => {
			Hashtable jsonObj = (Hashtable)JSON.JsonDecode(request.response.Text);
			if(jsonObj == null) 
			{
				Debug.LogError("server returned null or malformed response ):");
			}
		});
	}

But since I’m making a facebook version of this game it has to be able to post with HTTPS supported so I had to switch to the WWW and WWWForm method. I’ve got my GET function working already, but I’m a bit stuck with the POST. It keeps giving me a 400: BAD REQUEST. This is what I have

public void PostScore(string name, int score)
    {
        WWWForm form = new WWWForm();
        form.AddField("name", name);
        form.AddField("score", score);

        WWW www = new WWW("https://Mygame.firebaseio.com/scores.json", form);

        StartCoroutine(WaitForRequest(www));
    }

Can somebody help me out with this? Thanks! :slight_smile:

I’ve done for doing this below. Let’s go : ==>

using UnityEngine;

using UnityEngine.UI;

using System.Collections;

using System.Collections.Generic;

public class btnGetData : MonoBehaviour {

 void Start()
 {
     gameObject.GetComponent<Button>().onClick.AddListener(TaskOnClick);
 }
 IEnumerator WaitForWWW(WWW www)
 {
     yield return www;
    
     
     string txt = "";
     if (string.IsNullOrEmpty(www.error))
         txt = www.text;  //text of success
     else
         txt = www.error;  //error
     GameObject.Find("Txtdemo").GetComponent<Text>().text =  "++++++

" + txt;
}
void TaskOnClick()
{
try
{
GameObject.Find(“Txtdemo”).GetComponent().text = “starting…”;
string ourPostData = “{"plan":"TESTA02"”;
Dictionary<string,string> headers = new Dictionary<string, string>();
headers.Add(“Content-Type”, “application/json”);
//byte b = System.Text.Encoding.UTF8.GetBytes();
byte pData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
///POST by IIS hosting…
WWW api = new WWW(“http://192.168.1.120/si_aoi/api/total”, pData, headers);
///GET by IIS hosting…
///WWW api = new WWW(“http://192.168.1.120/si_aoi/api/total?dynamix={"plan":"TESTA02"”);
StartCoroutine(WaitForWWW(api));
}
catch (UnityException ex) { Debug.Log(ex.Message); }
}

}

Had to change something in the server settings to fix this problem. Works all fine now :smiley:

@deets can i see your php ? the string result works only on POSTMAN, it’s always null on unity.