排球 - 阻止方式的http请求

Fih*_*hop 17 post android http android-volley

我这几天正在学习如何使用Google排球.这对于快速联网非常方便.似乎所有请求都在Volley的后台运行.例如:

volleyRequestQueue.add(new JsonObjectRequest(Method.POST, SIGNUP_URL, reqBody, new SignUpResponseListener(), new MyErrorListener()));
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,我们可以进行以后台运行的POST调用(非阻塞方式).现在我的问题是:是否可以以阻止方式进行POST调用?为什么我需要一种阻止方式来进行REST调用?因为有些电话,比如登录,应该在做其他事情之前完成.

谢谢

Gab*_*iel 29

Volley通过RequestFutures支持阻止请求.您创建了一个普通请求,但将其回调设置为您的未来请求,这只是volley对标准Java期货的扩展.对future.get()的调用将阻止.

它看起来像这样

RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Method.POST, SIGNUP_URL, reqBody, future, future)
volleyRequestQueue.add(request);

try {
    JSONObject response = future.get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
Run Code Online (Sandbox Code Playgroud)

  • 因为我们将`RequestFuture` 传递给`JsonObjectRequest` 构造函数来代替成功和错误侦听器,这是否意味着当我们`future.get()` 时,我们必须手动区分成功和错误? (3认同)
  • 正如@John Cummings所提到的那样,你一定也应该阅读http://stackoverflow.com/questions/16904741/can-i-do-a-synchronous-request-with-volley上的讨论. (3认同)
  • 确切地说,它会在失败时抛出ExecutionException,你可以从异常中提取volley networkRequest对象来检查状态代码/请求体. (2认同)
  • 应该通过等待`future.get()`来处理`InterruptedException`,直到收到响应.为了清楚起见,我会编辑答案. (2认同)