我可以用 volley 做一个同步请求吗? [英] Can I do a synchronous request with volley?

查看:38
本文介绍了我可以用 volley 做一个同步请求吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在一个已经有后台线程的服务中.我可以在同一个线程中使用 volley 发出请求,以便回调同步发生吗?

Imagine I'm in a Service that already has a background thread. Can I do a request using volley in that same thread, so that callbacks happen synchronously?

有两个原因:

  • 首先,我不需要另一个线程,创建它会很浪费.
  • 第二,如果我在 ServiceIntent 中,线程的执行将在回调之前完成,因此我将不会收到 Volley 的响应.我知道我可以创建自己的服务,该服务有一些线程和我可以控制的运行循环,但最好同时拥有此功能.

推荐答案

看起来 Volley 的 RequestFuture 类是可能的.例如,要创建同步 JSON HTTP GET 请求,您可以执行以下操作:

It looks like it is possible with Volley's RequestFuture class. For example, to create a synchronous JSON HTTP GET request, you can do the following:

RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(), future, future);
requestQueue.add(request);

try {
  JSONObject response = future.get(); // this will block
} catch (InterruptedException e) {
  // exception handling
} catch (ExecutionException e) {
  // exception handling
}

这篇关于我可以用 volley 做一个同步请求吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆