Home > Enterprise >  API GET request through unity
API GET request through unity

Time:04-01

I have followed two different tutorial on how to get API requests with headers through Unity. One uses WWWForm and the other uses UnityWebRequest. I want to send my API-key through headers, it works with WWWForm, but I want to use UnityWebRequest instead.

The one with WWWForm(WWW class)

public class API: MonoBehaviour
{
    private const string url = "http://localhost/admin/activecodes";
    public const string API_KEY = "XXXXXXXX-XXXXX-XXXX-XXXX-XXXXXXXXXXXX";
    public Text responseText;

    public void Request()
    {   var www = UnityWebRequest.Get(url);
        WWWForm form = new WWWForm();

        Dictionary<string, string> headers = form.headers;
        headers["x-access-token"] = API_KEY;

        WWW request = new WWW(url, null, headers);
        // UnityWebRequest www = new UnityWebRequest(URL);
        StartCoroutine(OnResponse(request));
    }

    private IEnumerator OnResponse(WWW req)
    {
        yield return req;
        responseText.text = req.text;
        // responseText.text = req.downloadHandler.text;
    }
}

The one with UnityWebRequest:

using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using Newtonsoft.Json;

public class API : MonoBehaviour
{
    public Text responseText;
    public async void TestGet()
    {
        var url = "http://localhost/admin/activecodes";
        var API_KEY = "XXXXXXXX-XXXXX-XXXX-XXXX-XXXXXXXXXXXX";

        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers["x-access-token"] = API_KEY;


        using var www = UnityWebRequest.Get(url);
        
        www.SetRequestHeader("Authorization", headers.ToString());
        www.SetRequestHeader("Content-Type", "application/json");

        var operation = www.SendWebRequest();

        while (!operation.isDone)
        {
            await Task.Yield();
        }

        var jsonResponse = www.downloadHandler.text;

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError($"Failed: {www.error}");
        }

        try
        {
            var result = JsonConvert.DeserializeObject<List<ValidCodes>>(jsonResponse);
            Debug.Log($"Success: {www.downloadHandler.text}");
            foreach (var code in result)
            {
                responseText.text = code.activecode.ToString();
            }
            // return result;
        }
        catch (Exception ex)
        {
            Debug.LogError($"{this} Could not parse response {jsonResponse}. {ex.Message}");

        }
    }
}

CodePudding user response:

One mistake I can see is

www.SetRequestHeader("Authorization", headers.ToString());

headers is a Dictionary and ToString() won't give you the result you are expecting, you need to pass key as well to get the value headers["x-access-token"] will return your API_KEY.

However I don't see the point of using Dictionary here, you could just use your API_KEY directly like following.

www.SetRequestHeader("Authorization", API_KEY);

CodePudding user response:

Your first snippet makes little sense tbh. You are somehow mixing UnityWebRequest and (the obsolete) WWW and create a WWWForm that is nowhere used.


In the second snippet headers.ToString() will just return

System.Collections.Generic.Dictionary`2[System.String,System.String]

SetRequestHeader is indeed the equivalent for the items in the Dictionary<string,string> for the WWW.

So I think instead of introducing the new key "Authorization" you rather simply want to set this header with the same key and value as in the dictionary:

www.SetRequestHeader("x-access-token", API_KEY);

In general also you should check the result before you try and access the text like

if (www.result != UnityWebRequest.Result.Success)
{
    Debug.LogError($"Failed: {www.error}");
    return;
}

var jsonResponse = www.downloadHandler.text;
  • Related