Skip to content

Instantly share code, notes, and snippets.

@manuerumx
Last active October 20, 2021 05:39
Show Gist options
  • Save manuerumx/3e50fd3469e0684bde9c to your computer and use it in GitHub Desktop.
Save manuerumx/3e50fd3469e0684bde9c 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> 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);
}
}
}
@yoeven
Copy link

yoeven commented Oct 1, 2018

This helped a lot! Btw you used parameters.Add instead of your dictionary headers.

@jdnichollsc
Copy link

@Neelkukreti
Copy link

Thanks man Super helpful

@dracielisawal
Copy link

Thanks man Super helpful

True man, saved my ass too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment