-
-
Save habedi/6457854872b85ee5d4d4292f182eca01 to your computer and use it in GitHub Desktop.
Unity 3D example POST JSON Data to a Server with http Auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class goLevel : MonoBehaviour { | |
//With the @ before the string, we can split a long string in many lines without getting errors | |
private string json = @"{ | |
'hello':'world', | |
'foo':'bar', | |
'count':25 | |
}"; | |
void doPost(){ | |
string URL = "http://example.org/postData"; | |
string myAccessKey = "myAccessKey"; | |
string mySecretKey = "mySecretKey"; | |
//Auth token for http request | |
string accessToken; | |
//Our custom Headers | |
Dictionary<string,string> headers = new Dictionary<string, string>(); | |
//Encode the access and secret keys | |
accessToken = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes( myAccessKey + ":" + mySecretKey)); | |
//Add the custom headers | |
parameters.Add( "Authorization", "Basic " + accessToken); | |
parameters.Add( "Content-Type", "application/json" ); | |
parameters.Add( "AnotherHeader", "AnotherData" ); | |
parameters.Add ("Content-Length", json.Length.ToString()); | |
//Replace single ' for double " | |
//This is usefull if we have a big json object, is more easy to replace in another editor the double quote by singles one | |
json = json.Replace("'", "\""); | |
//Encode the JSON string into a bytes | |
byte[] postData = System.Text.Encoding.UTF8.GetBytes (json); | |
//Now we call a new WWW request | |
WWW www = new WWW(URL, postData, parameters); | |
//And we start a new co routine in Unity and wait for the response. | |
StartCoroutine(WaitForRequest(www)); | |
} | |
//Wait for the www Request | |
IEnumerator WaitForRequest(WWW www){ | |
yield return www; | |
if (www.error == null){ | |
//Print server response | |
Debug.Log(www.text); | |
} else { | |
//Something goes wrong, print the error response | |
Debug.Log(www.error); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment