Unity3d tutorial -GET and POST in Unity

POST method(with headers) in unity:

              In this article we are using JSON object to post data into Rest API, JSON can downloaded in      asset store.
            

               string url = "http://www.example.com/api/v1/user";
              WWWForm form = new WWWForm();

JSONObject request =new JSONObject();
request.AddField("Key",value);
             request.AddField("Key2",value);
             request.AddField("Key3",value);

              //we are converting JSON object to string
               blue=(request.ToString());
Debug.Log (blue);

             //we are converting String(blue) to BYTE
              byte[] rawData =System.Text.Encoding.UTF8.GetBytes(blue);

              //Adding headers using dictionary
               Dictionary<string,string> headers = form.headers;
headers ["Content-Type"]= "application/json";
WWW www = new WWW(url,rawData,headers);
StartCoroutine(WaitForRequest(www));


IEnumerator WaitForRequest(WWW www)
{
yield return www;
//Converting String ( www.text)  into JSON Object
JSONObject response =new JSONObject (www.text);

   }

POST method(without headers) in unity:

Post method in unity is same as Post with headers,we need to do some small changes in code.

             string url = "http://www.example.com/api/v1/user";
             WWWForm form = new WWWForm();
             //post values key and value pair
             
             form.AddField("Key",value);
            form.AddField("Key2",value);

             WWW www = new WWW(url,form);
             StartCoroutine(WaitForRequest(www));
  IEnumerator WaitForRequest(WWW www)
{
yield return www;
         //Converting String ( www.text)  into JSON Object

JSONObject response =new JSONObject (www.text);
        }

GET method in unity;

                     string url = "http://www.example.com/api/v1/user";
                     WWW www = new WWW(url);
                     StartCoroutine(WaitForRequest(www));

  IEnumerator WaitForRequest(WWW www)
{

yield return www;
//Converting String ( www.text)  into JSON Object
JSONObject response =new JSONObject (www.text);
        }



The exception can also be done  C# .




Comments