public void Send(RequestType type, string command, WWWForm wwwForm, RequestResponseDelegate onResponse = null, string authToken = "")
    {
        WWW request;

        #if UNITY_5_PLUS
        Dictionary <string, string> headers;
        #else
        Hashtable headers;
        #endif
        byte[] postData;
        string url = BackendUrl + command;
        Debug.Log("url..." + url);

        if (Secure)
        {
            url = url.Replace("http", "https");
        }

        if (wwwForm == null)
        {
            wwwForm  = new WWWForm();
            postData = new byte[] { 1 };
        }
        else
        {
            postData = wwwForm.data;
        }

        headers = wwwForm.headers;
        Debug.Log("headers..." + headers);

        //make sure we get a json response
        headers.Add("Accept", "application/json");

        //also add the correct request method
        headers.Add("X-UNITY-METHOD", type.ToString().ToUpper());

        //also, add the authentication token, if we have one
        if (authToken != "")
        {
            //for more information about token authentication, see: http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
            headers.Add("Authorization", "Token " + authToken);
        }
        request = new WWW(url, postData, headers);

        System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
        string callee = stackTrace.GetFrame(1).GetMethod().Name;
        StartCoroutine(HandleRequest(request, onResponse, callee));
        Debug.Log("request..." + request);
        Debug.Log("onResponse..." + onResponse);
        Debug.Log("callee..." + callee);
    }
Beispiel #2
0
    public void RequestObject(string UniqueTag, RequestResponseDelegate Callback)
    {
        GameObject outObj;

        if (StoredObjects.TryGetValue(UniqueTag, out outObj))
        {
            Callback(outObj);
            return;
        }
        List <RequestResponseDelegate> requestList;

        if (UnservicedRequests.TryGetValue(UniqueTag, out requestList))
        {
            requestList.Add(Callback);
        }
        else
        {
            requestList = new List <RequestResponseDelegate>();
            requestList.Add(Callback);
            UnservicedRequests.Add(UniqueTag, requestList);
        }
    }
Beispiel #3
0
    private IEnumerator HandleRequest(WWW request, RequestResponseDelegate onResponse, string callee)
    {
        //Wait till request is done
        while (true)
        {
            if (request.isDone)
            {
                break;
            }
            yield return(new WaitForEndOfFrame());
        }

        //catch proper client errors(eg. can't reach the server)
        if (!String.IsNullOrEmpty(request.error))
        {
            if (onResponse != null)
            {
                onResponse(ResponseType.ClientError, null, callee);
            }
            yield break;
        }
        int statusCode = 200;

        if (request.responseHeaders.ContainsKey("REAL_STATUS"))
        {
            string status = request.responseHeaders["REAL_STATUS"];
            statusCode = int.Parse(status.Split(' ')[0]);
        }
        //if any other error occurred(probably 4xx range), see http://www.django-rest-framework.org/api-guide/status-codes/
        bool   responseSuccessful = (statusCode >= 200 && statusCode <= 206);
        JToken responseObj        = null;

        try {
            if (request.text.StartsWith("["))
            {
                responseObj = JArray.Parse(request.text);
            }
            else
            {
                responseObj = JObject.Parse(request.text);
            }
        } catch (Exception ex) {
            if (onResponse != null)
            {
                if (!responseSuccessful)
                {
                    if (statusCode == 404)
                    {
                        //404's should not be treated as unparsable
                        Debug.LogWarning("Page not found: " + request.url);
                        onResponse(ResponseType.PageNotFound, null, callee);
                    }
                    else
                    {
                        Debug.Log("Could not parse the response, request.text=" + request.text);
                        Debug.Log("Exception=" + ex.ToString());
                        onResponse(ResponseType.ParseError, null, callee);
                    }
                }
                else
                {
                    if (request.text == "")
                    {
                        onResponse(ResponseType.Success, null, callee);
                    }
                    else
                    {
                        Debug.Log("Could not parse the response, request.text=" + request.text);
                        Debug.Log("Exception=" + ex.ToString());
                        onResponse(ResponseType.ParseError, null, callee);
                    }
                }
            }
            yield break;
        }

        if (!responseSuccessful)
        {
            if (onResponse != null)
            {
                onResponse(ResponseType.RequestError, responseObj, callee);
            }
            yield break;
        }

        //deal with successful responses
        if (onResponse != null)
        {
            onResponse(ResponseType.Success, responseObj, callee);
        }
    }
    private IEnumerator HandleRequest(WWW request, RequestResponseDelegate onResponse, string callee) {
        //Wait till request is done
        while (true) {
            if (request.isDone) {
                break;
            }
            yield return new WaitForEndOfFrame();
        }

        //catch proper client errors(eg. can't reach the server)
        if (!String.IsNullOrEmpty(request.error)) {
            if (onResponse != null) {
                onResponse(ResponseType.ClientError, null, callee);
            }
            yield break;
        }
        int statusCode = 200;
        
        if (request.responseHeaders.ContainsKey("REAL_STATUS")) {
            string status = request.responseHeaders["REAL_STATUS"];
            statusCode = int.Parse(status.Split(' ')[0]);
        }
        //if any other error occurred(probably 4xx range), see http://www.django-rest-framework.org/api-guide/status-codes/
        bool responseSuccessful = (statusCode >= 200 && statusCode <= 206);
        JToken responseObj = null;

        try {
            if (request.text.StartsWith("[")) { 
                responseObj = JArray.Parse(request.text); 
            } else { 
                responseObj = JObject.Parse(request.text); 
            }
        } catch (Exception ex) {
            if (onResponse != null) {
                if (!responseSuccessful) {
                    if (statusCode == 404) {
                        //404's should not be treated as unparsable
                        Debug.LogWarning("Page not found: " + request.url);
                        onResponse(ResponseType.PageNotFound, null, callee);
                    } else {
                        Debug.Log("Could not parse the response, request.text=" + request.text);
                        Debug.Log("Exception=" + ex.ToString());
                        onResponse(ResponseType.ParseError, null, callee);
                    }
                } else {
                    if (request.text == "") {
                        onResponse(ResponseType.Success, null, callee);
                    } else {
                        Debug.Log("Could not parse the response, request.text=" + request.text);
                        Debug.Log("Exception=" + ex.ToString());
                        onResponse(ResponseType.ParseError, null, callee);
                    }
                }
            }
            yield break;
        }

        if (!responseSuccessful) {
            if (onResponse != null) {
                onResponse(ResponseType.RequestError, responseObj, callee);
            }
            yield break;
        }
         
        //deal with successful responses
        if (onResponse != null) {
            onResponse(ResponseType.Success, responseObj, callee);
        }
    }
    //---- Private Methods ----//

    /// <summary>Performs a request to the backend.</summary>
    /// <param name="type">The request type(Get, Post, Update, Delete)</param>
    /// <param name="command">Command that is pasted after the url to backend. For example: "localhost:8000/api/" + command</param>
    /// <param name="wwwForm">A WWWForm to send with the request</param>
    /// <param name="onResponse">A callback which will be called when we retrieve the response</param>
    /// <param name="authToken">An optional authToken which, when set will be put in the Authorization header</param>
    public void Send(RequestType type, string command, WWWForm wwwForm, RequestResponseDelegate onResponse = null, string authToken = "") {
        WWW request;
#if UNITY_5_PLUS
        Dictionary<string, string> headers;
#else
        Hashtable headers;
#endif
        byte[] postData;
        string url = BackendUrl + command;

        if (Secure) {
            url = url.Replace("http", "https");
        }

        if (wwwForm == null) {
            wwwForm = new WWWForm();
            postData = new byte[] { 1 };
        } else {
            postData = wwwForm.data;
        }

        headers = wwwForm.headers;
        
        //make sure we get a json response
        headers.Add("Accept", "application/json");

        //also add the correct request method
        headers.Add("X-UNITY-METHOD", type.ToString().ToUpper());

        //also, add the authentication token, if we have one
        if (authToken != "") {
            //for more information about token authentication, see: http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
            headers.Add("Authorization", "Token " + authToken);
        }
        request = new WWW(url, postData, headers);

        System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
        string callee = stackTrace.GetFrame(1).GetMethod().Name;
        StartCoroutine(HandleRequest(request, onResponse, callee));
    }