- Home /
Cannot get data from HTTP Response using UnityWebRequest in Unity
Hey Unity PROs, I am beginner here! I am trying to use the Microsoft Bing Text to Speech API in Unity, this API requires an AccessToken that will be passed in the request header. to get this token, I have sent my Authentication Key in the "Ocp-Apim-Subscription-Key" header, and the the API will return back the access token that i can use next, this is a test of the API that retuns the Token in Postman.
So this is the code to do this, but it doesn't work.
using System.Collections;
using System.Collections.Generic;
using System.Xml.Linq;
using UnityEngine;
using UnityEngine.Networking;
public class Test : MonoBehaviour
{
public static readonly string accessUri = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
public string accessToken;
public void Start()
{
WWWForm wwwForm = new WWWForm();
Dictionary<string, string> headers = wwwForm.headers;
headers["Ocp-Apim-Subscription-Key"] = "a66ec1e2efed47639f22e2dc2e760d13x";
UnityWebRequest www = UnityWebRequest.Post(accessUri, wwwForm);
StartCoroutine(RequestToken(www));
}
public IEnumerator RequestToken(UnityWebRequest www)
{
yield return www;
if (www.error == null)
{
Debug.Log("downloadedBytes : " + www.downloadedBytes);
Debug.Log("certificateHandler : " + www.certificateHandler);
Debug.Log("chunkedTransfer : " + www.chunkedTransfer);
Debug.Log("downloadHandler : " + www.downloadHandler);
Debug.Log("downloadProgress : " + www.downloadProgress);
Debug.Log("isDone : " + www.isDone);
Debug.Log("isNetworkError : " + www.isNetworkError);
Debug.Log("method : " + www.method);
Debug.Log("redirectLimit : " + www.redirectLimit);
Debug.Log("responseCode : " + www.responseCode);
Debug.Log("uploadedBytes : " + www.uploadedBytes);
Debug.Log("useHttpContinue : " + www.useHttpContinue);
}
else
{
Debug.Log("Error" + www.error);
}
var p = www.downloadHandler.data;
Debug.Log("Access token: " + p);
}
}
The result of this code :
I have already tried the WWW class, but this didn't work! and the System.Net.Http, but Unity wont accept this Library :/
Is there any way to do that, please?
Answer by Martin_Gonzalez · Mar 30, 2018 at 09:46 PM
You are not passing the headers anywhere.
Try doing something like this:
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("User-Agent", "Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 55.0.2883.87 Safari / 537.36");
WWWForm formData = new WWWForm();
formData.AddField("UserName", "Programmer");
formData.AddField("Password", "ProgrammerPass");
WWW www = new WWW("http://www.thismachine.info/", formData.data, headers);
yield return www;
Debug.Log(www.text);