Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

WWW/WWWForm to post json data to server [SOLVED]

Discussion in 'Scripting' started by magnetix, Aug 15, 2010.

  1. magnetix

    magnetix

    Joined:
    Apr 4, 2010
    Posts:
    102
    After checking out a bunch of pages on how to post xml and json using WWWForm, I just cannot get a valid response from the server. It always gives me an error code 500.

    The following curl command structure works:

    Code (csharp):
    1. curl --verbose --request POST --header "Content-Type: text/json" --data @newScore.json [url]https://myurl[/url]
    newScore.json looks something like this:
    Code (csharp):
    1. { score:1000, nickname:"nn" }
    Please can someone help me get this into a JS script? Here's what I have so far...

    Code (csharp):
    1. var postScoreURL = "https://myurl";
    2. var jsonString = "{ score:1000, nickname:\"nn\" }";
    3.  
    4. var encoding = new System.Text.UTF8Encoding();
    5. var postHeader = new Hashtable();
    6.    
    7. postHeader.Add("Content-Type", "text/json");
    8. postHeader.Add("Content-Length", jsonString.Length);
    9.  
    10. print("jsonString: " + jsonString);
    11.  
    12. var request = WWW(postScoreURL, encoding.GetBytes(jsonString), postHeader);
    13.  
    14. yield request;
    15.    
    16. // Print the error to the console
    17. if (request.error != null)
    18. {
    19.     Debug.Log("request error: " + request.error);
    20. }
    21. else
    22. {
    23.     Debug.Log("request success");
    24.     Debug.Log("returned data" + request.data);
    25. }
    26.  
    It prints out "request success" but the server responds the data contains an error 500. Can anyone help please? The curl command works, so the server seems to be ok...
     
    PerlKr likes this.
  2. magnetix

    magnetix

    Joined:
    Apr 4, 2010
    Posts:
    102
    So actually this script works. I removed the Content-Length line but the problem I was having was an incorrect key value in my actual data that was failing a check on the server.

    Parsing the json returned is another matter but there are posts already with answers on that topic.

    EDIT: http://forum.unity3d.com/viewtopic.php?t=37637
     
  3. magnetix

    magnetix

    Joined:
    Apr 4, 2010
    Posts:
    102
    What the heck - here's how I got the info out using MiniJSON:
    Code (csharp):
    1.     var requestString : String = "{\"status\":201,\"someKey\":\"someValue\"}";
    2.  
    3.     var jsonKeys : Hashtable = MiniJSON.JsonDecode(requestString);
    4.  
    5.     for(key in jsonKeys.Keys)
    6.     {
    7.         Debug.Log("key: " + key);
    8.         Debug.Log("value: " + jsonKeys.Item[key]);
    9.     }
    10.    
    11.     print("status: " + jsonKeys.Item["status"]);

    prints:

    Code (csharp):
    1. someKey
    2. someValue
    3. status
    4. 201
    5. status: 201
    Stick the MiniJSON C# script in a folder called "Standard Assets" (just create the folder if not already there). That way it will be compiled before the other scripts to allow usage from within your javascript scripts.

    Hopefully this gives a decent explanation of how to do all this now :)
     
  4. Ezequiel

    Ezequiel

    Joined:
    Jan 28, 2014
    Posts:
    1
    Just changed the "Content-Type" header field:

     
  5. philunity

    philunity

    Joined:
    Apr 23, 2014
    Posts:
    1
    Just check your input data in your json string. Maybe "score" or "nickname" is not set in your server. Maybe its "username" instead of "nickname" or something like that. :p
     
  6. speedacidrain

    speedacidrain

    Joined:
    May 4, 2015
    Posts:
    4
    Link not found
     
    jrussek likes this.
  7. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,453
    6 years later, and on different forum software. Imagine that..... :rolleyes:
     
  8. kmfjsc

    kmfjsc

    Joined:
    Nov 30, 2016
    Posts:
    1
    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 = "++++++\n\n" + txt;
    }

    void TaskOnClick()
    {
    try
    {
    GameObject.Find("Txtdemo").GetComponent<Text>().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); }
    }

    }