“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay who are based in Denmark...”

Rob Lacey
Senior Software Engineer, UK

C# HTTP API calls from inside Unity

Had to fiddle about a bit to work out how to POST an JSON API with Unity via C#, this example sends raw JSON with the application/json header which Rails will then decode it and turn it into ‘params’.

using UnityEngine;
using System.Collections;

public class ThingAPI : MonoBehaviour {
	// Use this for initialization
	IEnumerator Start () {
		// GET
                var url = "http://localhost:3000/api/posts/1";
		WWW www = new WWW(url);
		yield return www;

                // POST
		url = "http://localhost:3000/api/posts";
		var jsonString = "{\"post\":[{\"title": "Something to post about\": 1, \"body\": \"and maybe someone will listen to my cries.\"}]}";
		
		var encoding = new System.Text.UTF8Encoding();
		var postHeader = new Hashtable();
		
		postHeader.Add("Content-Type", "application/json");
		postHeader.Add("Content-Length", jsonString.Length);

		www = new WWW(url, encoding.GetBytes(jsonString), postHeader);
		yield return www;
	}
}