Search code examples
c#unity-game-enginewebrequesttin-can-api

Unity C# webRequest with JSON& xAPI


I'm implementing an xAPI test article within Unity using c# with UnityWebRequest and have run into an issue that i can't seem to resolve.

When i Post to http://httpbin.org/post my calls function as expected and the JSON data recieved by the server is also exactly as expected.

When i change the endpoint to https://lrs.adlnet.gov/xapi/ (xAPI statement viewer) my calls return 200 | OK but do not show up. I've validated that the endpoint, authentication and JSON appropriate. (Same data sends fine using the xAPI stringbuilder as well as my own HTML/Javascript test articles.

When i change the endpoint to my SCORM cloud LRS endpoint, i get error 400 | Unknown/Generic HTTP Error but nothing else that's helpful.

PostMethod

public static IEnumerator IPostLRSData(string jsonData, string authKey, string endpoint, Action<string> callback = null) {
        UnityWebRequest request = new UnityWebRequest(endpoint, UnityWebRequest.kHttpVerbPOST);
        //byte[] bodyRaw = new UTF8Encoding().GetBytes(jsonData);
        //byte[] bodyRaw = new ASCIIEncoding().GetBytes(jsonData);
        byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);

        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

        request.SetRequestHeader("Authorization", authKey);
        request.SetRequestHeader("X-Experience-API-Version", xAPIUtils.XAPI_VERSION);
        request.SetRequestHeader("Content-Type", "application/json");

        yield return request.Send();

        if(request.isNetworkError || request.isHttpError) {
            Debug.LogWarning(request.error);
        } else {
        // Show results as text
            Debug.LogWarning(request.downloadHandler.text);
        }

        callback(request.responseCode + " | " + request.error);
    }

As a madness last attempt i ported a github threaded WebRequest example and tailored it to my project and with it i get similar results as above except it falls silent with the last 2 endpoints. even in debug mode.


Solution

  • Based on what you have provided as your "endpoint" it seems like you need to append the resource that you are requesting, in your case it would be /statements. Consider using TinCan.NET as a library, or at least looking at its implementation since it is OSS. http://rusticisoftware.github.io/TinCan.NET/