1

I'm working with an http-based API and want to know when I encounter any errors. I'm using Android-Query (stub):

AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
        @Override
        public void callback(String url, JSONObject json, AjaxStatus status) {
            try {
                if (json != null) { 
                    if (json.getString("authenticated") != "true")
                        // An error, but status=200 and json!=null

            } catch (JSONException e) { errors... } } };

And I'm using it like this:

    final AQuery aq = new AQuery(this);
    aq.ajax(url, JSONObject.class, cb);
    cb.block();

My questions are:

  • I've found that using cb.block() is the only way to get the library to work synchronously, but I'm not sure it's the best way (it feels like it isn't).
  • The callback method can't throw exceptions, can't return anything (void) etc, so what is the best way to handle errors? I noticed it supports cb.getResult() but it looks like calling this method causes the outside block to return (I can't explain it).

Thanks.

4

1 回答 1

3

所以在我花了一些时间使用这个库之后,它看起来支持同步 HTTP 请求。虽然我同意这不是大多数情况下的最佳实践,但说这完全是一个坏主意就是忽略了一些可能需要它的条件。在我的情况下,我依赖于我无法控制的其他库,这不在 UI 线程中,所以没关系。

AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();
final AQuery aq = new AQuery(this);
cb.url(url).type(JSONObject.class);
aq.sync(cb);

JSONObject json = cb.getResult();
AjaxStatus status = cb.getStatus();
if (json != null && statusValid(status)) {
    // parse json object, throw if fails, etc.
}
于 2013-07-09T08:43:33.447 回答