Unity3D C# WWW class: execute code after every request

ε祈祈猫儿з 提交于 2019-12-11 23:08:11

问题


I couldn't find any clues for this online as I suppose a lot of people have abandoned Unity's WWW class for complex stuff. I'm using the WWW class to talk to my REST API, and I need to find a way to execute some code after every request. (I need to check the response code and execute some default behaviour if the response is 401)

Is there a simple way to achieve this?

(I'm using coroutines to send the requests)

Thanks in advance.

Update: Current code sample

Auth.cs:

public IEnumerator Login(WWWForm data, Action<APIResponse> success, Action<APIResponse> failure)
    {
        WWW request = new WWW (API + "auth/authenticate", data);
        yield return request;
        if (request.responseHeaders ["STATUS"] == "HTTP/1.1 401 Unauthorized") {
            //Do something, I want to do this on every request, not just on this login method
        }
        if (request.error != null) {
            failure (new APIResponse(request));
        }
        else {
            //Token = request.text.Replace("\"", "");
            Token = request.text;
            Debug.Log (Token);
            success (new APIResponse (request));
        }

    }

Usage:

StartCoroutine (auth.Login (data, new Action<APIResponse> (response => {
            //Do stuff

        }), new Action<APIResponse> (response => {
            //Do stuff
        })));

回答1:


I am not using WWW with rest api to achieve the "async" way, using the time out and exception handling works for me:

public static string PostJson(string host, string resourceUrl, object json)
{
    var client = new RestClient(host);
    client.Timeout = Settings.LIGHT_RESPONSE_TTL; //set timeout duration

    var request = new RestRequest(resourceUrl, Method.POST);
    request.RequestFormat = DataFormat.Json;
    request.AddBody(json);

    try
    {
        var response = client.Execute(request);
        return response.Content;
    }
    catch (Exception error)
    {
        Utils.Log(error.Message);
        return null;
    }

}

To consume this function:

var result = JsonUtils.PostJson("http://192.168.1.1:8080", "SomeEndPoints/abc/def", jsonString);
if (string.IsNullOrEmpty(result))
{
     //Error
}
else
{
      //Success
}

Update: to make sure such calls do not block the UI, use below code:

Loom.RunAsync(() => {
    var result = JsonUtils.PostJson("http://192.168.1.1:8080", "SomeEndPoints/abc/def", jsonString);
    if (!string.IsNullOrEmpty(result)) {

    }
});

You can download Loom here. Example use of such code can be demonstrated with below GIF animation, note that the UI (circular indicator) is not blocked!



来源:https://stackoverflow.com/questions/33013341/unity3d-c-sharp-www-class-execute-code-after-every-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!