Skip to content

Instantly share code, notes, and snippets.

@nooralibutt
Created November 17, 2015 09:07
Show Gist options
  • Save nooralibutt/37ccb3e424d8d9948bed to your computer and use it in GitHub Desktop.
Save nooralibutt/37ccb3e424d8d9948bed to your computer and use it in GitHub Desktop.
Unity Get Post Methods of Getting/Posting data to server written in C#
using UnityEngine;
using System.Collections;
public class RequestService : MonoBehaviour
{
public string GetUrl = "http://hmkcode.appspot.com/rest/controller/get.json";
public string PostUrl = "http://androidexample.com/media/webservice/httppost.php";
public string textRetrieved;
void RequestGet ()
{
WWW www = new WWW (GetUrl);
Debug.Log ("Process Get Request ... ");
StartCoroutine (WaitForGetRequest (www));
}
void RequestPost ()
{
WWWForm form = new WWWForm();
form.AddField("name", "Noor Ali Butt");
form.AddField("email", "nooralibutt@gmail.com");
form.AddField("user", "nooralibutt");
form.AddField("pass", "test123");
WWW www = new WWW(PostUrl, form);
Debug.Log ("Process Post Request ... ");
StartCoroutine(WaitForPostRequest(www));
}
IEnumerator WaitForGetRequest (WWW www)
{
yield return www;
// check for errors
if (www.error == null) {
string text = www.text;
textRetrieved = text;
Debug.Log ("WWW Ok!: \n" + text);
} else {
Debug.Log ("WWW Error: " + www.error);
}
}
IEnumerator WaitForPostRequest (WWW www)
{
yield return www;
// check for errors
if (www.error == null) {
string text = www.text;
textRetrieved = text;
Debug.Log ("WWW Ok!: " + www.text);
} else {
Debug.Log ("WWW Error: " + www.error);
}
}
void OnGUI ()
{
// Make a background box
GUI.Box (new Rect (10, 10, 200, 200), "Services Test");
// Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
if (GUI.Button (new Rect (20, 40, 120, 30), "Request Get")) {
RequestGet ();
}
// Make the second button.
if (GUI.Button (new Rect (20, 70, 120, 30), "Request Post")) {
RequestPost ();
}
GUI.Label(new Rect(Screen.width/2, Screen.height/2, 200, 200), textRetrieved);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment