【问题标题】:Unity3D C# WWW class: execute code after every requestUnity3D C# WWW 类:每次请求后执行代码
【发布时间】:2016-01-05 22:20:47
【问题描述】:

我在网上找不到任何线索,因为我想很多人已经放弃了 Unity 的 WWW 类来寻找复杂的东西。我正在使用 WWW 类与我的 REST API 对话,并且我需要找到一种方法来在每个请求之后执行一些代码。 (如果响应为 401,我需要检查响应代码并执行一些默认行为)

有没有简单的方法来实现这一点?

(我正在使用协程发送请求)

提前致谢。

更新:当前代码示例

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));
        }

    }

用法:

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

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

【问题讨论】:

  • 更新了我的帖子以包含一些代码。

标签: c# web unity3d webrequest


【解决方案1】:

我没有使用带有 rest api 的 WWW 来实现“异步”方式,使用超时和异常处理对我有用:

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;
    }

}

使用此功能:

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

更新:为确保此类调用不会阻塞 UI,请使用以下代码:

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

    }
});

您可以下载 Loom here。此类代码的示例使用可以用下面的 GIF 动画演示,注意 UI(圆形指示器)没有被阻塞!

【讨论】:

  • 我认为 Unity 不支持 RestSharp,如果我错了请纠正我,但我认为它不会在 iOS 上运行。
  • 绝对支持,把.net框架改成3.5。在播放器设置中,我已经这样做了数百万次,:)。此外,您应该使用与 .net 3.5 兼容的版本的 RestSharp,您可以从 github 或其他地方轻松下载。
  • 你也可以试试 JsonFX!
  • 啊完美!但是我真的不想在请求比预期时间长一点时阻塞 UI,你有使用这个库的异步示例吗?
  • 如果你在非 ui 线程中运行它,它根本不会阻塞 ui。我确实有一个示例,它在发布 json 时显示一个圆形指示器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 2014-12-07
  • 2017-02-01
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多