Skip to content

Instantly share code, notes, and snippets.

@Neelkukreti
Forked from manuerumx/postJSON.cs
Created June 9, 2020 22:27
Show Gist options
  • Save Neelkukreti/aeacb93f7de39a7282b87940190f4bbc to your computer and use it in GitHub Desktop.
Save Neelkukreti/aeacb93f7de39a7282b87940190f4bbc to your computer and use it in GitHub Desktop.
Unity 3D example POST JSON Data to a Server with http Auth
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> parameters = 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