Skip to content

Instantly share code, notes, and snippets.

@deadlyfingers
Created April 13, 2018 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deadlyfingers/8fadd8c17b2ca5179e1f54b211c5d618 to your computer and use it in GitHub Desktop.
Save deadlyfingers/8fadd8c17b2ca5179e1f54b211c5d618 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
[RequireComponent(typeof(TextMesh))]
public class PostTester : MonoBehaviour {
private TextMesh textmesh;
[SerializeField]
private string key;
private string result;
bool needsUpdate = false;
StringBuilder log = new StringBuilder();
// Use this for initialization
void Start () {
textmesh = gameObject.GetComponent<TextMesh>();
if(string.IsNullOrEmpty(key))
{
Log("Requires key!");
needsUpdate = true;
return;
}
SendRequest();
}
// Update is called once per frame
void Update () {
if (!needsUpdate)
{
return;
}
textmesh.text = log.ToString();
needsUpdate = false;
}
public void SendRequest()
{
StartCoroutine(RequestToken());
StartCoroutine(PostToken());
}
private void Log(string text, bool isError=false)
{
if (!isError) {
Debug.Log(text);
} else {
Debug.LogError(text);
}
log.AppendLine(text);
needsUpdate = true;
}
// Unity 2017.3.1 responds with "Generic/unknown HTTP error"
// https://issuetracker.unity3d.com/issues/networking-unitywebrequest-dot-post-returns-generic-slash-unknown-http-error?page=1#comments
// Note: UnityWebRequest does not currently support POSTs with no data. You still need to use the WWW class for this?
IEnumerator RequestToken()
{
Debug.Log("UWR POST");
using (UnityWebRequest www = UnityWebRequest.Post("https://api.cognitive.microsoft.com/sts/v1.0/issueToken", ""))
{
www.SetRequestHeader("Ocp-Apim-Subscription-Key", key);
www.chunkedTransfer = false;
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Log("UWR Error: " + www.error);
}
else
{
// Save token as result
result = www.downloadHandler.text;
Log ("UWR Token:\n" + result);
}
}
}
IEnumerator PostToken()
{
Debug.Log("WWW POST");
var headers = new Dictionary<string, string>();
headers.Add("Ocp-Apim-Subscription-Key", key);
headers.Add("Content-Type", "application/x-www-form-urlencoded");
var form = new WWWForm();
// This is the workaround for empty post body otherwise Unity responds with error: "Cannot create a data handler without payload data"
form.AddField("", "");
using (WWW www = new WWW("https://api.cognitive.microsoft.com/sts/v1.0/issueToken", form.data, headers))
{
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
Log("WWW Error: " + www.error);
}
else
{
// Save token as result
result = www.text;
Log("WWW Token:\n" + result);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment