RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, null, future, future);
requestQueue.add(request);
it will always block you can use future.get(30, TimeUnit.SECONDS); after that time it will throw timeout exception rather than waiting indefinitely
try {
JSONObject response = future.get(); // this will block (forever)
} catch (InterruptedException e) {
// exception handling
} catch (ExecutionException e) {
// exception handling
}
Volley是一个非常优秀的网络框架,不仅可以发送异步请求,同步请求同样也非常好用。下面这段代码应该在子线程中调用,否则将会阻塞。
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest("http://vjson.com", future, future);
VjsonVolley.addRequest(request);
try {
String result = future.get();
//future.get(timeout, unit)
Log.d(MainActivity.class.getSimpleName(), result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
#